5

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

2
  • If yours is working code, you should better ask your question on codereview.stackexchange.com Commented Oct 23, 2016 at 22:31
  • 1
    A mysql connection is even used persistently over multiple http requests. Everything else would indeed be a huge performance issue. That means that closing the connection would actually slow things down. Commented Oct 23, 2016 at 22:33

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.