PDO可以通过设置ATTR_ERRODE属性来控制sql执行出错时的行为表现,具体可以设置以下三个值:
PDO::ERRMODE_SILENT 静默模式,不会报错,只会设置PDO的 errorCode
PDO::ERRMODE_WARNING 会报warning错误
PDO::ERRMODE_EXCEPTION 抛出异常
下面来看代码演示:
1、静默模式
<?php
try {
$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', 'root', [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
} catch (PDOException $e) {
exit('连接数据库失败:' . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$sql = "SELECT id FROM not_a_table LIMIT 1";
$rs = $pdo->query($sql);
var_dump($pdo->errorCode());
print_r($pdo->errorInfo());
执行结果:
string(5) "42S02"
Array
(
[0] => 42S02
[1] => 1146
[2] => Table 'test.not_a_table' doesn't exist
)
------------------------------------------------------------------------------------------------------------------------------------------------------------------
2、warning模式
<?php
try {
$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', 'root', [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
} catch (PDOException $e) {
exit('连接数据库失败:' . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
ini_set('display_errors', 'On');
$sql = "SELECT id FROM not_a_table LIMIT 1";
$rs = $pdo->query($sql);
var_dump($pdo->errorCode());
print_r($pdo->errorInfo());
执行结果:
Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.not_a_table' doesn't exist in E:\project\slim\web\pdo.php on line 16
string(5) "42S02" Array ( [0] => 42S02 [1] => 1146 [2] => Table 'test.not_a_table' doesn't exist )
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
3、抛出异常:
<?php
try {
$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', 'root', [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
} catch (PDOException $e) {
exit('连接数据库失败:' . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id FROM not_a_table LIMIT 1";
try {
$rs = $pdo->query($sql);
} catch (PDOException $e) {
echo 'sql执行出错:' . $e->getCode() . '###' . $e->getMessage() . "\n";
}
var_dump($pdo->errorCode());
print_r($pdo->errorInfo());
执行结果:
sql执行出错:42S02###SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.not_a_table' doesn't exist
string(5) "42S02"
Array
(
[0] => 42S02
[1] => 1146
[2] => Table 'test.not_a_table' doesn't exist
)
由于PDO抛出的是PDOException,所以我们的代码中尽量不要自己手动抛出PDOException,以免混淆。