PDO Connection Test
Query:
Can PDO be utilized to test valid and invalid database connections? Here's a code snippet that attempts the connection:
try{ $dbh = new pdo('mysql:host=127.0.0.1:3308;dbname=axpdb','admin','1234'); die(json_encode(array('outcome' => true))); }catch(PDOException $ex){ die(json_encode(array( 'outcome' => false, 'message' => 'Unable to connect' ))); }
However, the script keeps attempting the connection until the execution time limit (60 seconds) is reached, instead of indicating a connection failure.
Answer:
To establish a proper database connection with PDO, you need to specify the error mode during the connection process:
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 error mode to "exception" (PDO::ERRMODE_EXCEPTION), any connection errors will be raised as exceptions. This allows you to catch these exceptions and handle them gracefully, providing a more informative error message than simply waiting for the timeout.
For further information on these topics, refer to the provided links:
The above is the detailed content of Can PDO be Used to Test Database Connection Validity?. For more information, please follow other related articles on the PHP Chinese website!