I am establishing a database connection in php using the function
$DBConn = mysql_connect ("localhost" , "testuser" , "test123")
At the time of releasing the connection I am using
if( is_resource($DBConn) )
to check whether the connection is currently set or not. I want to know is it efficient to do this or I should check the connection like this
if( $DBConn )
I want to know prod and cons of using both the statements.
First of all, you should no longer be using mysql_xxx functions; there are many articles out there that discuss the benefits of having prepared statements, etc. with PDO / mysqli.
By looking at the manual, it states that it returns a link identifier or false on failure. You shouldn't make assumptions as to what exactly this identifier is, it's usually a resource but it may as well be an object or integer. I would simply negate the easier condition:
if (false !== $DBConn) {
// do something with the database
}
Or, alternatively:
if (false === $DBConn) {
throw new Exception("Could not connect to database");
}
// do something with the database
Edit
Using if ($DBConn) { ... } is okay as well, because it's basically the opposite of 0, false, null, "" and empty array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With