$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // 问题:默认为POD::ERRMODE_SILENT,但是当未设置错误级别时,php抛出了Fatal error???? $name = 'Seven'; $sql = 'SELECT * FROM user WHERE user_name =:name'; // 数据表名有误 $stmt = $dbh->prepare($sql); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->execute(); $code = $stmt->errorCode(); //var_dump($code);echo '<br>'; // 输出错误码,string(5) "42S02" if (empty($code)) { while ($row = $stmt->fetchObject()) { echo $row['id'],"\t",$row['name'],"\t",$row['score'],"<br>"; } }else{ echo'Error occurred when execut SQL ', $sql, '<br>'; echo'ErrorInfo:<br><pre>'; var_dump($stmt->errorInfo()); }
执行脚本结果:
1 2 3 4 5 6 7 8
Error occurred when execut SQL SELECT * FROM user WHERE user_name =:name<br>ErrorInfo:<br><pre>array(3) { [0]=> string(5) "42S02" [1]=> int(1146) [2]=> string(32) "Table 'seven.user' doesn't exist" }
当未设置错误级别时,输出结果为:
1 2 3 4 5
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seven.user' doesn't exist' in /home/cdyf/tutorial/PDO/Pdo_test.php:119 Stack trace: #0 /home/cdyf/tutorial/PDO/Pdo_test.php(119): PDOStatement->execute() #1 {main} thrown in /home/cdyf/tutorial/PDO/Pdo_test.php on line 119
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $name = "Seven"; $sql = 'SELECT * FROM user WHERE user_name =:name'; $stmt = $dbh->prepare($sql); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->execute(); $code = $stmt->errorCode(); // var_dump($code);echo '<br>'; if (empty($code)) { while ($row = $stmt->fetchObject()) { echo $row['id'],"\t",$row['name'],"\t",$row['score'],"<br>"; } }else{ echo'Error occurred when execut SQL ', $sql, '<br>'; echo'ErrorInfo:<br><pre>'; var_dump($stmt->errorInfo()); }
执行脚本结果:
1 2 3 4 5 6 7 8 9
PHP Warning: PDOStatement::execute(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seven.user' doesn't exist in /home/cdyf/tutorial/PDO/Pdo_test.php on line 157 Error occurred when execut SQL SELECT * FROM user WHERE user_name =:name<br>ErrorInfo:<br><pre>array(3) { [0]=> string(5) "42S02" [1]=> int(1146) [2]=> string(32) "Table 'seven.user' doesn't exist" }