Connect to a MySQL Database Tutorial

Learn how to connect to a database via PHP

Connecting to a database via PHP 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, this way you will be able to perform the change easily.

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

This will create three variables in PHP that will store the different MySQL connection details.

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

With this line PHP connects to the MySQL database server at localhost with the provided username and password.

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. To select a database, you can use the following command:

With the above PHP uses the MySQL connection and with it - selects 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".

Another important PHP function is:

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. Thus 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.