Connecting to the Database Server
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 three strings: the hostname, a username, and a password. If you omit any or all of 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", "root", "n1ckel" ); 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.