Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method I should use and why?

Tags:

php

mysql

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.

like image 290
Mayank Avatar asked May 21 '26 02:05

Mayank


1 Answers

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.

like image 139
Ja͢ck Avatar answered May 23 '26 14:05

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!