Connecting to the Database with PHP

The first step in doing anything to the database, is establishing a connection to the database. This is because the database is a seperate program from the web server, and may even be on a seperate computer.

To establish a connection, you need to know several things from when you set up your database:

Database Connection Example

Most PHP developers will create a database connection file which we can import into any file where we need to access the database. It will look something like this:

<?php
$hostname = "localhost";	// localhost when the DB server is on the same server as the site
$database = "salesDB";
$username = "mylogin";
$password = "n@tUr3P@$s";
$db_connection = mysql_connect($hostname, $username, $password) 
	or die('Could not connect to to database: ' .mysql_error());

mysql_select_db($database, $db_connection);
?>

The PHP Code Explained

the variables - Variables like $hostname = "localhost"; are designed to make it easier to write the connection command and parameters.

mysql_connect() - This command connects PHP to the database server. For it to work, you have to pass the host where the server is located, the username and the password.

or die - This command looks for an error. While we rarely get an error, if we pass in the correct credentials, we can still sometimes get an error if there is a problem connecting to the server. Since this will cause an issue, we have an "or die()" command which halts execution of the page, and allows us to display an error message.

mysql_error() - This command returns the exact error message from trying to connect to the server. I've added a string to make sure that this information is clear.

mysql_select_db() - This is used to choose which database, on the database server, we are trying to connect to. We have to specify the database name, as well as the connection object which is used.