我在PHP中收到以下错误:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'localhost' (10061)' in C:\xampp\htdocs\project\Service\Database.class.php:26 Stack trace: #0 C:\xampp\htdocs\project\Service\Database.class.php(26): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:\xampp\htdocs\project\Service\Database.class.php(54): Service\Database::initialize() #2 C:\xampp\htdocs\project\index.php(15): Service\Database::getHandler() #3 {main} thrown in C:\xampp\htdocs\project\Service\Database.class.php on line 26
错误本身不是问题,我故意终止Windows中的MySQL服务,看看发生了什么(我正在使用XAMPP)。问题是我无法捕获PDO对象抛出的异常,我不知道为什么。
try {
$host = "localhost";
$dbname = "project";
$userName = "root";
$password = "";
$charset = "utf8";
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
);
// This is the line that supposedly throws the exception (LINE 26):
$dbh = new PDO($dsn, $userName, $password, $driverOptions);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::setHandler($dbh);
} catch (PDOException $e) {
die("CATCHED"); // This line is never reached
} catch (Exception $e) {
die("CATCHED"); // nor this one.
}
我在这里缺少什么?
答案 0 :(得分:16)
我唯一能想到的是,如果你在一个命名空间的类中,并且应该使用\PDOException
而不是PDOException
。
答案 1 :(得分:2)
启用error_reporting并检查错误。
ini_set('display_errors', true);
error_reporting(E_ALL);
在该行之前可能存在致命错误,或者可能PDO不可用。