Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mysqli persistent connection across different pages

Tags:

php

mysql

mysqli

I have a web app that uses different PHP pages to process code.

At the top of each page, I open a mysqli connection to the same database (with the same user/password):

$link = mysqli_connect("$mysql_server", "$mysql_user", "$mysql_pw", "$mysql_db");
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

I understand it's better to use a single persistent connection. How can I enable this across all pages?

Is it has easy as just using $link = mysqli_connect("p:" . $mysql_server, "$mysql_user", "$mysql_pw", "$mysql_db"); for the first connection?

Under what circumstances would this connection close?

like image 780
alias51 Avatar asked Dec 26 '22 14:12

alias51


2 Answers

$db = mysqli_connect("p:notlocalhost","notroot","","catalog") or die("Error " . mysqli_error($link));

It is "p:" - when prepended before hostname, creates persistent connection. That is later reused on different pages. You still call same constructor on every page.

like image 136
lot Avatar answered Dec 28 '22 09:12

lot


You don't understand the meaning of persistent connection. Nobody says you can use once created PHP resource across the pages, which is surely impossible. Persistent connection has an inner technical meaning for the PHP-DBMS interconnection and does not affect your code in any way.

To avoid writing the same code on different pages you can use include operator to include some sort of bootstrap file with all the common code and settings, including your db connection code as well.

As for the persistent connection - avoid it for a while as it can do more harm than good if used without knowledge.

Also note that you should never address a variable using quotes. $mysql_user is a variable but "$mysql_user" is a string which is not the same.

like image 37
Your Common Sense Avatar answered Dec 28 '22 09:12

Your Common Sense