Home >Database >Mysql Tutorial >How to Make PDO Report Database Connection Errors?
PDO Connection Testing
Query:
Can PDO be utilized to validate and invalidate database connections? A PHP script is provided that attempts to connect to a database but stalls instead of reporting a connection error.
Solution:
In order for PDO to properly report connection errors, it is necessary to set the error mode explicitly:
try { $dbh = new pdo( 'mysql:host=127.0.0.1:3308;dbname=axpdb', 'admin', '1234', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) ); die(json_encode(array('outcome' => true))); } catch (PDOException $ex) { die(json_encode(array('outcome' => false, 'message' => 'Unable to connect'))); }
By setting the ERRMODE attribute to EXCEPTION, PDO will throw an exception when a connection error occurs. This allows for error handling and avoids the script from timing out.
Additional Information:
The above is the detailed content of How to Make PDO Report Database Connection Errors?. For more information, please follow other related articles on the PHP Chinese website!