Everything PHP: Connecting to MySQL

Published on Jul 9, 2009   //  Development
Off

Everything PHP

We have now gone over database structures and how to create our database. Since we’ve covered those essentials, we can now dive into the PHP side of databases. The PHP side of databases is where all the interesting stuff begins, so stay tuned through the next couple of articles to learn more.

Before we can start performing queries on our MySQL database using PHP, we need to initiate a connection to it. The process to do this is straight forward. We first connect to MySQL using our username and password. Once the connection has been established, we can then select the desired database that we want to work off of.

The outline of the process goes like this: connect to MySQL, ensure connection was success, select database and ensure selecting the database was successful. We’ll be using the mysql_connect() and mysql_select_db() functions. Let’s look at what connecting to MySQL and selecting a database would look like:

[code language="php"]$mysql_host = 'localhost'; // The host of MySQL (usually 'localhost')
$mysql_user = 'user'; // The MySQL username
$mysql_password = 'password'; // The associated password for the MySQL username
$mysql_db = 'database'; // The name of the database you would like to work with

$link = mysql_connect( $mysql_host, $mysql_user, $mysql_password );
if (!$link) {
die('An error occurred while connecting to MySQL.');
}

$select = mysql_select_db( $mysql_db, $link );
if (!$select) {
die('An error occurred while selecting the database.');
}
// If you get to here, MySQL has been connected to and the database selected[/code]

There you have it, you have successfully established a connection to a MySQL database in PHP. Next week we’ll be going over querying a database.