Start the task in mySQL and PHP to avoid connecting to the database on each page

I am coding a simple php / mysql webpage that is page1.php, page2.php, etc. Since I use a database on every page (or at least 90% of them), I place a standard database on it

mysql_connect("localhost"," "," "); mysql_select_db(" "); . . mysql_close(); 

with my inquiries.

My question is: do I really need to connect to the database on every page, or is there a way to avoid this and stay connected? Some of the pages are linked to others, and I can use SESSIONS to publish some variables, but my question translates into something more globalized.

+8
sql php mysql
source share
4 answers

You can use mysql_pconnect for a permanent connection, although it does not help you with this, and it can be a big pain to do it right. It is almost simply better to connect it on every page, especially if the database server is running on the same computer as the php server.

+6
source share

The network is offline in nature. This means that you have no idea whether the client will return for the second request or not.

No matter what you absolutely want to connect / disconnect from the database on each individual page. This is the only way to ensure that you are not experiencing connection leaks and that the site can remain responsive.

Most systems are designed to handle the connection pool, which makes the process of requesting a new connection very fast, so you have nothing to worry about.

+7
source share

Try using

 mysql_pconnect() 

From php.net

"acts very similar to mysql_connect () with two main differences.

Firstly, when connecting, the function will first try to find a (permanent) link that is already open with the same host, username and password. If it is found, the identifier for it will be returned instead of opening a new connection.

Secondly, the connection to the SQL server will not be closed when the script completes. Instead, the link will remain open for future use (mysql_close () will not close the links set by mysql_pconnect ()). "

+1
source share

If you just want to make it so that you don’t have to hardcode it at the beginning of each file, write the connection code in the file and then use require /path/to/file/name.php and it will install it every time Note: It can be turned on and not needed.

+1
source share

All Articles