Page 1 of 1

PDO & fatal errors

Posted: Tue Dec 24, 2013 12:29 pm
by social_experiment
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.

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);
?>
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

Code: Select all

<?php
 if (is_object($dbh)) {
   // i can go on and interact with the database
 }
?>
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.

Re: PDO & fatal errors

Posted: Tue Dec 24, 2013 2:09 pm
by Weirdan
Docs say that failure to establish database connection will always result in exception. Could it be that you're catching and then ignoring the exception caught?

Re: PDO & fatal errors

Posted: Tue Dec 24, 2013 3:59 pm
by Celauran
If your class depends on PDO, I'd catch the PDO exception and throw it again. No point instantiating a class you can't use.

Re: PDO & fatal errors

Posted: Tue Dec 24, 2013 7:41 pm
by Celauran
Better still, require it as a constructor argument. Creating the PDO object shouldn't be this class's responsibility.

Re: PDO & fatal errors

Posted: Wed Dec 25, 2013 5:17 pm
by social_experiment
Weirdan wrote:Could it be that you're catching and then ignoring the exception caught?
I don't understand what you're saying here; i do catch the exception but the ignoring part? Below is the code that i use when creating the PDO instance.

Code: Select all

<?php
try {
	$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);					
}
catch (Exception $e) {
	// Better message.
	echo 'Cannot establish connection to database';
        // ^ this displays when i alter the connection details
}
?>
Celauran wrote:Creating the PDO object shouldn't be this class's responsibility.
Sounds like a better option than what i am currently doing, how would i then check if the argument passed was indeed a PDO object? Would is_object() suffice or type hinting?

Re: PDO & fatal errors

Posted: Wed Dec 25, 2013 10:13 pm
by Celauran
I'd use type hinting over is_a. is_object is too vague, IMO.

Re: PDO & fatal errors

Posted: Thu Dec 26, 2013 4:33 am
by social_experiment
thanks for the suggestion :)