如何在创建“新PDO”之前检查凭据是否正确或数据库是否存在

时间:2017-03-31 14:54:22

标签: php mysql pdo

$dbname='database_name';

$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';
$con = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$con->query("SET NAMES 'utf8'");

如何检查database_name,database_user,database_password是否正确或数据库是否存在。

1 个答案:

答案 0 :(得分:3)

正如有人建议的那样,使用try / catch:

$dbname='database_name';
$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    // if you do not want to output message you can log the errors
    echo $e->getMessage();
    $errorCode = $e->getCode();
}