[ Team LiB ] Previous Section Next Section

Connecting to the MySQL Database Server

MySQL is a popular open-source database. As a consequence, it has become one of the foundations of open-source Web development. PHP no longer bundles MySQL but remains a perfect partner for it.

Because PHP is not bundled with MySQL, you should make certain that it is present on your system. You can get MySQL together with all its installation instructions from http://www/mysql.com/.

To ensure that PHP works with MySQL you should configure it using the - -with-mysql flag, like so:


./configure - -with-mysql

If the previous fragment does not work for you, you may need to specify a path to the MySQL directory, like this:


./configure - -with-mysql=/path/to/mysql/dir

You will need to add your own path, of course, but this should be enough to get MySQL working with PHP.

Before you can begin working with your database, you must first connect to the server. PHP provides the mysql_connect() function to do just this. mysql_connect() does not require any arguments but accepts up to five. The first three arguments are strings: a hostname, a username, and a password. The fourth optional argument is a Boolean. If you pass true for this, every call to mysql_connect() returns a new connection. Otherwise, mysql_connect() returns the currently open connection for all calls that use the same arguments. The fifth optional argument enables you to pass integer flags directly to the MySQL server.

If you omit these arguments, the function assumes localhost as the host and that no password or username has been set up in the mysql user table, unless defaults have been set up in the php.ini file. Naturally, this is unwise for anything but a test database, so we will always include a username and password in our examples. mysql_connect() returns a link resource if the connection is successful. You can store this return value in a variable so that you can continue to work with the database server.

The following code fragment uses mysql_connect() to connect to the MySQL database server:


$link = mysql_connect( "localhost", "p24_user", "cwaffie" );
if ( ! $link ) {
  die( "Couldn't connect to MySQL" );
}

If you are using PHP in conjunction with Apache, you could also connect to the database server with mysql_pconnect(). From the coder's perspective, this function works in exactly the same way as mysql_connect(). In fact, there is an important difference. If you use this function, the connection does not die when your script stops executing or if you call mysql_close() (which ends a standard connection to the MySQL server). Instead, the connection is left active, waiting for another process to call mysql_pconnect(). In other words, the overhead of opening a new connection to the server can be saved if you use mysql_pconnect() and a previous call to the script has left the connection open.

    [ Team LiB ] Previous Section Next Section