PDO & fatal errors
Posted: Tue Dec 24, 2013 12:29 pm
I'm using PDO to connect to a database, handle database interactions and i'm not sure how to handle the errors (fatal) that result when no connection to a database can be established.
If there is an error connecting to the database then no PDO object is created which causes a fatal error when using for instance prepare()
Fatal error: Call to a member function prepare() on a non-object in...
My thinking is to check whether $dbh is an object, and based on that continue with the process, something like
Is this approach correct or should i be looking at something different, and if so, what would you recommend?
Some more information that might be relevant - i'm creating an instance of a PDO object inside the construct of a class which i then set as class property so most of my checking would be done inside other class methods.
Code: Select all
<?php
$dbh = new PDO('mysql:host=localhost;dbname=est', $user, $pass);
// meanwhile somewhere else in the code
$countSql = "SELECT COUNT(`id`) FROM `user_main` WHERE
`username` = ?";
$sth = $dbh->prepare($countSql);
?>Fatal error: Call to a member function prepare() on a non-object in...
My thinking is to check whether $dbh is an object, and based on that continue with the process, something like
Code: Select all
<?php
if (is_object($dbh)) {
// i can go on and interact with the database
}
?>Some more information that might be relevant - i'm creating an instance of a PDO object inside the construct of a class which i then set as class property so most of my checking would be done inside other class methods.