Here is my code:
<?php try{ // connect to database and select database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "spy"; $dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $dbh_conn->exec("set names utf8"); $dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?> My code works as well. But I seen a similar code which checks the connection like this:
if ( !$dbh_conn ){ // Something Went Wrong } else { // All Fine } Well do I need to this ^ condition? Or using try catch is enough to check db connection?
$dbh_connin the following lines, if establishing the connection itself didn't work. That you tried to call methods like exec and setAttribute on a non-object will only cause standard error messages, but no exceptions either.