你好 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 的全部 gyst 然后担心使它更容易使用!随着重复,“漫长的道路”会更多地理解代码。不要一开始就偷工减料,一旦你明白你在做什么,就削减它们!
$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 的全部内容。希望有帮助!
也看看这个。这对我帮助太大了!
我也将其用作参考(有时)-该网站看起来很垃圾,但那里有关于 PDO 的质量信息。我也用这个,我发誓这是最后一个链接!因此,在此之后,任何问题都可以提出,但希望这可以成为 PDO 的一点参考指南。(希望哈哈)