You should establish a connection to the MySQL database. This is an extremely important step because if your script cannot connect to its database, your queries to the database will fail.

A good practice when using databases is to set the username, the password and the database name values at the beginning of the script code. If you need to change them later, it will be an easy task.

$username="your_username";$password="your_password";$database="your_database";

You should replace “your_username”, “your_password” and “your_database” with the MySQL username, password and database that will be used by your script.

At this point you may be wondering if it is a security risk to keep your password in the file. You don’t need to worry because the PHP source code is processed by the server before being sent to the browser. So the visitor will not see the script’s code in the page source.

Next you should connect your PHP script to the database. This can be done with the mysql_connect PHP function:

mysql_connect(localhost,$username,$password);

This line tells PHP to connect to the MySQL database server at ‘localhost’ (localhost is the MySQL server which usually runs on the same physical server as your script).

After the connection is established you should select the database you wish to use. This should be a database to which your username has access to. This can be completed through the following command:

@mysql_select_db($database) or die( "Unable to select database");

It tells PHP to select the database stored in the variable $database (in our case it will select the database “your_database”). If the script cannot connect it will stop executing and will show the error message:

Unable to select database

The ‘or die’ part is useful as it provides debugging functionality.  However,  it is not essential.

Another important PHP function is:

mysql_close();

This is a very important function as it closes the connection to the database server. Your script will still run if you do not include this function. And too many open MySQL connections can cause problems for your account. This it is a good practice to close the MySQL connection once all the queries are executed.

You have connected to the server and selected the database you want to work with. You can start querying the database now.