你好ButterDog让我带你通过PDO一步一步来。
步骤1)
创建一个名为connect.php文件(或你想要什么都)。这个文件将在每个需要数据库交互的php文件中被需要。
让我们开始也请注意我的意见:
?php
//We set up our database configuration
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password
// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=xxxxx;dbname=xxxxx", $username, $password); // Construct the PDO variable using $dbh
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set attributes for error reporting very IMPORTANT!
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Set this to false so you can allow the actual PDO driver to do all the work, further adding abstraction to your data interactions.
?>
步骤2)要求connect.php请看一看:
require ('....../........./...../connect.php'); // Require the connect script that made your PDO variable $dbh
步骤3)
启动数据库的交互只需执行以下操作,请阅读代码注释。目前我们不会担心数组问题!获得PDO的完整体验,然后担心使其更易于使用!随着重复,“漫长的路程”对代码有了更多的了解。一开始就不要偷工减料,一旦明白自己在做什么,就切断它们!
$query = $dbh->prepare("SELECT * FROM note_system WHERE note = :cnote"); // This will call the variable $dbh in the required file setting up your database connection and also preparing the query!
$query->bindParam(':cnote', $cnote); // This is the bread and butter of PDO named binding, this is one of the biggest selling points of PDO! Please remember that now this step will take what ever variable ($cnote) and relate that to (:cnote)
$query->execute(); // This will then take what ever $query is execute aka run a query against the database
$row = $query->fetch(PDO::FETCH_ASSOC); // Use a simple fetch and store the variables in a array
echo $row['yourvalue']; // This will take the variable above (which is a array) and call on 'yourvalue' and then echo it.
这就是所有有PDO.希望这有助于!
也看看this。这对我非常有帮助!
我也使用this作为参考(有时) - 网站看起来像垃圾,但有关于PDO的质量信息。我也使用this,我发誓这是最后一个环节!所以在这个问题出现之后,只要问一下,但希望这可以变成PDO的一个参考指南。(希望笑)
[参见手册](http://php.net/manual/en/mysqli.prepare.php) – Kermit
PHP手册首先让我感到困惑。这就是我来这里问这个问题的原因。 – ButterDog
希望我的回答清除了一些东西...祝你好运先生 –