None of our previous PHP tutorials have dealt with a database yet, and that is for the sole reason that not everyone has access to a database, however for those who do this tutorial will teach you the basics on how you can connect to your database. We wont be covering SQL queries and the conversion of SQL queries into PHP in this tutorial, you can look for a tutorial on that later on. Before we begin it’s important to note that this tutorial is geared towards those of you who are utilizing PHP 5.4 or earlier. As of PHP 5.5 the mysql_* functions are deprecated and I highly recommend you utilize the methods within our PHP Data Objects tutorial. First I suggest we get the hang of this.
Lets start by defining some variables. We will need to define the
$dbuser, $dbpass, $dbhost and
$db variables (at least those are the names I always use – you can obviously set the names of these variables to anything you want). These will hold the username and password for access to the database, the database host (99% of the time its localhost) and the database name. Here is how we accomplish this:
$dbuser = "mysql_username"; $dbpass = "mysql_password"; $dbhost = "localhost"; $db = "db_name";
Now we just fill in the username, password, host (if needed), and database name with our own information.
Now we can use those variables to connect to the MySQL server. To do this we need to follow the
mysql_connect format of host, username, password.
mysql_connect($dbhost, $dbuser, $dbpass);
Now we need to select the database we wish to work with. We do this with the
function. Now if you know any SQL queries now is a perfect time to run them. When you are finished you can close the connect with the
mysql_close(); function. Here is the complete code:
$dbuser = "mysql_username"; $dbpass = "mysql_password"; $dbhost = "localhost"; $db = "db_name"; mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($db); // Query etc goes here mysql_close();