PHP SQL Connect

This statement opens a connection to the database server. The "mysql_connect" or "mysql_pconnect" statements may be used to do this. I recommend that the "mysql_connect" statement be normally used except for special circumstances. This is because the "mysql_pconnect" statement is used to establish a permanent connection to the database. The "mysql_close" statement will NOT end connections opened with the "mysql_pconnect" statement. If you use the "mysql_pconnect" statement to connect to your database on your website, you may start getting errors stating that you have too many connections open to the database and additional connections will be refused.

PHP SQL Connect Statement Syntax

The syntax for the mysql_connect statement is shown below. This statement will open a connection to the server. The "mysql_select_db" statement must be used later to select the database on the server to be used.

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

PHP SQL Connect Statement Example

In this example, a connection is made to the database using the user called "username", with a passsword of "password". You will want to use a unique password. The name "localhost" is used to specify that the database is on the same server that the PHP program is running on. This is your webserver. The handle to the database is returned in the variable "$chandle". If the call fails, the string contained after the "or die" part of the statement will be executed and program execution will stop.

$dbname="mydata";  //the name of the database
$chandle = mysql_connect("localhost", $dbuser, $dbpass) 
    or die("Connection Failure to Database");
echo "Connected to database server<br>";
mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found." . $dbuser);
echo "Database " .  $database . " is selected";