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.
Non persistent connection closes when the execution of the script is over.
When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.
In short, for every request you have to connect.
IMHO, use PHP's SPL's PDO library if possible for a database connection. By using its prepared statements you can exclude SQL injection.
Check out the singleton example in the bellow link for a simplest implementation.
http://www.php.net/manual/en/class.pdo.php