$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是否正确或数据库是否存在。
答案 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();
}