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?
$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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With