如何使用PDO连接到MySQL数据库,如何检查它是否已成功连接?

时间:2012-12-06 09:14:27

标签: php mysql pdo

// 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连接到数据库。

3 个答案:

答案 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)

将您的$handle更改为...

   new PDO('mysql:host=....

......不......

   new PDO('mysql:dbName=...

您可以找到示例here