We will talk about PDO::ERRMODE. This attribute controls the error reporting mode. It have three value: PDO::ERRMODE_SILENT, PDO::ERRMODE_WARNING, and PDO:ERRMODE_EXCEPTION. Ok, let’s talk about them.
PDO::ERRMODE_SILENT: when there is error, no action is taken. The error codes are available via PDO::errorCode() and PDO::errorInfo(). It is default value for PDO::ATTR_ERRMODE.
<?php // configuration $dbhost = "localhost"; $dbname = "pdo"; $dbuser = "root"; $dbpass = ""; // database connection $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // query $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); $sql = "SELECT * FROM booksa"; $q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo())); $r = $q->fetch(PDO::FETCH_ASSOC); print_r($r); //result: //ERROR: 42S02:1146:Table 'test.booksa' doesn't exist ?>
PDO::ERRMODE_WARNING: No action is taken, but an error will be raised with E_WARNING level.
// query $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $sql = "SELECT * FROM booksa"; $q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo())); $r = $q->fetch(PDO::FETCH_ASSOC); print_r($r); //result: //Warning: PDO::query() [function.PDO-query]: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.booksa' doesn't exist in //C:\AppServ5\www\test\pdo\test.php on line 15 //ERROR: 42S02:1146:Table 'test.booksa' doesn't exist
PDO::ERRMODE_EXCEPTION: will set the error codes (as with PDO::ERRMODE_SILENT) and en exception of class PDOException will be thrown.
// query $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * FROM booksa"; $q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo())); $r = $q->fetch(PDO::FETCH_ASSOC); print_r($r); //result: //Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.booksa' doesn't exist' in //C:\AppServ5\www\test\pdo\test.php:15 Stack trace: #0 C:\AppServ5\www\test\pdo\test.php(15): PDO->query('SELECT * FROM b...') #1 {main} thrown in //C:\AppServ5\www\test\pdo\test.php on line 15
// query $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * FROM booksa"; $q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo())); $r = $q->fetch(PDO::FETCH_ASSOC); print_r($r); //result: //Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.booksa' doesn't exist' in //C:\AppServ5\www\test\pdo\test.php:15 Stack trace: #0 C:\AppServ5\www\test\pdo\test.php(15): PDO->query('SELECT * FROM b...') #1 {main} thrown in //C:\AppServ5\www\test\pdo\test.php on line 15
0 comments:
Post a Comment