Reference — Frequently Asked Questions about PDO: Handling Errors
As a PHP Data Objects (PDO) user, it's essential to know how to effectively handle errors. This article addresses a common question regarding error detection in PDO.
PDO Query Fails but I Can't See Any Errors. How to Get an Error Message from PDO?
To obtain error messages from PDO, you need to set the error mode to exceptions. Exceptions provide several advantages over regular errors, including:
Example:
$dsn = "mysql:host=$host;dbname=$db;charset=utf8"; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Other options ]; $pdo = new PDO($dsn, $user, $pass, $opt); try { // Execute your PDO query here } catch (PDOException $e) { echo "Error: " . $e->getMessage() . "\n"; }
Important Notes:
The above is the detailed content of PDO Query Fails Silently: How Can I Get Error Messages?. For more information, please follow other related articles on the PHP Chinese website!