Is this the correct code to close my MySQL connection?

My code appears to work just fine but from time to to time I have database connection errors or to many connections to my database which hangs my sites (every few month’s)

Does the code below look ok?

Thank you
Kevin…

<?php
$user_name = "myusername";
$password = "mypassword";
$database = "mydatabase";
$server = "mysql.myhost.com";
$db_handle = ($GLOBALS["connection"] = mysqli_connect($server,  $user_name,  $password)); 
$db_found = ((bool)mysqli_query( $db_handle, "USE " . $database)); 

if ($db_found) {
	$SQL = "SELECT * FROM master WHERE ((name like '%".$SeachFor."%')) ORDER BY ccrandomnum DESC LIMIT 2000" ;
	$result = mysqli_query($GLOBALS["connection"], $SQL); 
?>

//my main code here

<?php
((is_null($___mysqli_res = mysqli_close($db_handle))) ? false : $___mysqli_res); 
}
else 
{
print "Database NOT Found ";
((is_null($___mysqli_res = mysqli_close($db_handle))) ? false : $___mysqli_res); 
}
?>

You don’t want to do this: $GLOBALS[“connection”]

What you want is a singleton database connection. You call a method requesting a db connection. If one is available the class hands it off, if it isn’t it creates one and gives you that.

Will using $GLOBALS[“connection”] cause an issue or is it just bad programming??

I got the code from the web and I really do not really know what $GLOBALS is really doing in the first place.

Thank you
Kevin…

Bad programming that could* lead to issues. If another part of the site changes that value, you have no idea where it happens. That is the reason all global variables are bad.

OK, Thank you I will work on getting that cleaned up.

So does this part of my code look ok? I want to verify that I closing everything correctly.

Thanks again
Kevin…

<?php ((is_null($___mysqli_res = mysqli_close($db_handle))) ? false : $___mysqli_res); } else { print "Database NOT Found "; ((is_null($___mysqli_res = mysqli_close($db_handle))) ? false : $___mysqli_res); } ?>

[php]mysqli_close($db_handle)[/php]

Is sufficient. I don’t use mysqli and only use PDO, unless I have a reason not to do so.

PDO explicitly closes connections when they are finished executing and the resource is no longer needed.

Thank you

Here is the problem:

I got the code from the web

Take some time and learn what your doing. Start here: https://phpdelusions.net/pdo

Sponsor our Newsletter | Privacy Policy | Terms of Service