我是PHP的新手,在學習完該語言的基礎知識之後,我已經學習了一些關於PDO的教程,並且只是想知道我的代碼是否正確,以及你們建議我可以改變它以使它更加完善安全,更快,更高效,你的名字...這是PDO好的代碼(PHP)嗎?
我遵循大量的教程來實現這個結果,因此我想我會問你們,因爲不是PHP上的每個Web上的教程(有這樣的很多)是學習最佳實踐和編寫優秀代碼的可靠來源。
這是我的代碼。它只將字符串'Bill Gates'插入到名爲'pdotest',表'tableOne'和行'rowOne'的數據庫中。我使用了持久數據庫連接,因爲這應該會使Web應用程序更快。我敢肯定,你們可以啓發我如何正確使用這個持久連接的東西,我可能還沒有完全理解如何在我的代碼中使用它。
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
try {
$conn = new PDO('mysql:host=localhost;dbname=pdotest', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
// Data to insert (Bill Gates = Hero #1)
$data = 'Bill Gates';
try {
// The insert query
$sql = "INSERT INTO tableone (rowOne) VALUES (:rowOne)";
$q = $conn->prepare($sql);
$q->execute(array(':rowOne'=>$data));
// Example INSERT query with multiple VALUES
// $q->execute(array(':rowOne'=>$data, ':rowTwo'=>$dataTwo));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
?>
這個問題似乎是題外話,因爲它是關於代碼審查 – SergeS
這個問題似乎是題外話,因爲它是http://codereview.stackexchange.com/ – easwee