Home >Backend Development >PHP Tutorial >How Can I Retrieve PDO Prepare() Query Errors in PHP?
Retrieving Query Errors from prepare() in PDO PHP
When using PDO PHP to prepare a query, it's essential to check for any potential errors. By default, PDO doesn't throw exceptions for errors encountered during query preparation. To enable error handling, you can leverage the PDO::ATTR_ERRMODE attribute.
Solution
Example:
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
If the provided query contains invalid syntax, PDO will throw an exception with the following information:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.doesnotexist' doesn't exist
The above is the detailed content of How Can I Retrieve PDO Prepare() Query Errors in PHP?. For more information, please follow other related articles on the PHP Chinese website!