Home >Database >Mysql Tutorial >How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?
Problem:
Consider the following PHP code:
$st = $db->prepare("SELECT * FROM c6ode");
How can you obtain the intended MySQL error for the query in this instance?
Solution:
To retrieve error information from prepare(), you must:
Here's an example:
<?php $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 (?)');
This code will throw an exception and print the following error message:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.doesnotexist' doesn't exist
The above is the detailed content of How to Retrieve MySQL Errors from PDO's `prepare()` Method in PHP?. For more information, please follow other related articles on the PHP Chinese website!