Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I keep reconnecting to mysql in PHP?

Tags:

oop

php

mysql

class

I have a pretty large site and every page is built from several included files, my site is 100% in a procedural format and I am trying to learn to use classes and a more OOP approach in PHP.

Currently my site has a header file that is included into every page, in this header is a mysql connection that is made and last the duration of the page, so if I need to run 10 different queries from different files, they all run without needing to make a new connection, so the connection is only made once.

Now that I am trying to convert to a more OO way, I am starting with writing a mysql class to connect and run queries, so I am thinking of using the classes __construct function to make a connection to mysql, I am just curious how this would work though, everytime that class gets called it would make or try to make a connection to mysql instead of just once.

Maybe I am not thinking it out clearly. Should I just initiate this class in the header 1 time and then I wont have to worry anymore?

like image 210
JasonDavis Avatar asked Sep 09 '09 06:09

JasonDavis


People also ask

Should I close MySQL connection PHP?

If your script has a fair amount of processing to perform after fetching the result and has retrieved the full result set, you definitely should close the connection. If you don't, there's a chance the MySQL server will reach it's connection limit when the web server is under heavy usage.

Why should we close database connection PHP?

Closing connections prevents them to be used for connection pooling, so "stalkers" (i.e. other processes requiring a database connection) cannot reuse them.

What is the use of MySQL connection in PHP?

PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established or null.

How long do MySQL connections last?

MySQL has its wait_timeout variable default value set to 28800 seconds (8 hours).


1 Answers

You could create a single global object of your MySQL class and use that object everywhere. Then your constructor would only be called once.

Or you could create new objects of your MySQL class everywhere. mysql_connect doesn't open new connections if there already is one open:

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

like image 72
Christian Davén Avatar answered Oct 06 '22 16:10

Christian Davén