Specifications
Setting Up a Connection
We use this line in our script to connect to the MySQL server:
@ $db = mysql_pconnect(“localhost”, “bookorama”, “bookorama”);
We have used the mysql_pconnect() function to connect to the database. This function has the
following prototype:
int mysql_pconnect( [string host [:port] [:/socketpath] ] ,
[string user] , [string password] );
Generally speaking, you will pass it the name of the host on which the MySQL server is run-
ning, the username to log in as, and the password of that user. All of these are optional, and if
you don’t specify them, the function uses some sensible defaults—localhost for the host, the
username that the PHP process runs as, and a blank password.
The function returns a link identifier to your MySQL database on success (which you ought to
store for further use) or false on failure. The result is worth checking as none of the rest of
code will work without a valid database connection. We have done this using the following
code:
if (!$db)
{
echo “Error: Could not connect to database. Please try again later.”;
exit;
}
An alternative function that does almost the same thing as mysql_pconnect() is
mysql_connect(). The difference is that mysql_pconnect() returns a persistent connection
to the database.
A normal connection to the database will be closed when a script finishes execution, or when
the script calls the
mysql_close() function. A persistent connection remains open after the
script finishes execution and cannot be closed with the mysql_close() function.
You might wonder why we would want to do this. The answer is that making a connection to a
database involves a certain amount of overhead and therefore takes some time. When
mysql_pconnect() is called, before it tries to connect to the database, it will automatically
check if there is a persistent connection already open. If so, it will use this one rather than
opening a new one. This saves time and server overhead.
It is also worth noting that persistent connections don’t persist if you are running PHP as a
CGI. (Each call to a PHP script starts a new instance of PHP and closes it when the script fin-
ishes execution. This also closes any persistent connections.)
Using MySQL
P
ART II
234
13 7842 CH10 3/6/01 3:36 PM Page 234