Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/MYSQL - Multiple connections to the same database?

I have two files:

config.php:

$con = mysqli_connect("$dbhost","$dbuser","$dbpass","$dbname");

ads.php (config.php require_once):

$query1 = mysqli_query($con,"SELECT * From XXXX where id = 'XXXX'");

$query2 = mysqli_query($con,"SELECT * FROM XXXX2 WHERE id = 'XXXX2'");

I have more than 40 different queries mysqli_query() using $con. Please keep in mind that all my logic is procedural style, not object oriented.

My two questions are:

  1. am I connecting to the DB using a different connection on every query? Or just once when the first one is executed? Is there a better way to do this?

  2. I understand that it is not mandatory to close a mysql connection since it closes itself, however since we have millions of consults sometimes a few can hang and stay for more than 10 seconds after the user left the PHP file. If I wanted to close a connection, should I put mysqli_close($con) at the end of the file (after the 40 consults) or at the end of each consult (40 times)?

Any help would be appreciated. Thanks

like image 419
Lucas Avatar asked Oct 29 '22 18:10

Lucas


1 Answers

You are reusing the connection initiated in mysqli_connect.

A better way could be to use or create a DataHandler and implement PDOs. It could allow you to perform timing analytics on queries, automate binding parameters, destroy the connection once its finished with etc.

Call mysqli_close($con) at the end of the file. Also null $con to mark for garbage collection.

Once finished with the information from each step you could also call; mysqli_free_result($query1) to free memory associated to the statement handle

like image 200
atoms Avatar answered Nov 09 '22 13:11

atoms