// your database's server
define("SERVER", "localhost");
// your database's name
define("DATABASE", "CS50");
// your database's username
define("USERNAME", "root");
// your database's password
define("PASSWORD", "");
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
我正在开发一个项目,我必须使用PDO连接到数据库。
答案 0 :(得分:1)
$user = "username";
$pass = "password";
$host = "localhost";
$db = "yourDbname";
$dns = "mysql:host=" . $host . ";dbname=" . $db;
$dbh = new PDO($dns, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
当你必须进行查询时(只是一个例子):
$theid = 10;
$statement = $dbh->prepare('SELECT * FROM yourtable WHERE id = ? and name = ?');
$statement->execute(array($theid,'baronth'));
如果你想在连接或查询时看到是否有一些错误(并且你知道try-catch是如何工作的),请用它包围:
try {
all the code that you wan't to check
}
catch (PDOException $e) {
echo $e->getMessage();
}
它会回应错误。
答案 1 :(得分:0)
<?php
/* Provoke an error -- bogus SQL syntax */
$handle = $dbh->prepare('bogus sql');
if (!$handle) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
?>
答案 2 :(得分:0)