Home >Database >Mysql Tutorial >How to Retrieve SQL Errors from PDO Prepared Statements in PHP?
Retrieving SQL Errors in PDO/Prepare in PHP
To check for intentional errors in MySQL queries using the prepare() method in PDO PHP, follow these steps:
1. Set the Error Mode Attribute
Set the error mode attribute to PDO::ERRMODE_EXCEPTION using the setAttribute() method to enable exception handling. This will cause the prepare method to throw an exception if an error occurs:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
2. Disable Emulation
Disable PDO::ATTR_EMULATE_PREPARES by setting it to false. This is necessary because the MySQL server may not evaluate the prepared statement until execution, making it harder to detect errors:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Example:
The following code prepares the query "SELECT * FROM c6ode" and throws an exception if the table c6ode does not exist:
try { $st = $db->prepare("SELECT * FROM c6ode"); } catch (PDOException $e) { // Handle the exception and display the error message }
Exception Output:
Executing the above code (with c6ode not existing) will print an exception message indicating that the table does not exist:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.c6ode' doesn't exist
The above is the detailed content of How to Retrieve SQL Errors from PDO Prepared Statements in PHP?. For more information, please follow other related articles on the PHP Chinese website!