Jim Taylor

Intuitive PHP for the caffeinated.

Archive for the ‘Intermediate’ Category

Connecting to a MySQL Database

One of the most important things about websites today is the ability for them to access dynamic information. Knowing how to connect to your database will enable you to write applications that deal directly with database information, and the possibilities are endless.

There are four bits of information that you will want to know when building your connection function. Name, login, password, and host. Below will be an example of code that I use often in applications.

<?php

//Insert your database information.
$db =”foobase”; //Database Name
$dbuser =”someuser”; //Database Login
$dbpass =”thepassword”; //Database password
$dbhost =”localhost”; //Database Host Information

function dbConnect($db) {
global $dbhost, $dbuser, $dbpass;

$dbcnx =@mysql_connect($dbhost, $dbuser, $dbpass)
or die(”The site database appears to be down.”);

if ($db !=”" and !@mysql_select_db($db))
die(”The site database is unavailable”);

return $dbcnx;

?>

These four initial variables require your database information. The function calls these up in order to work. You can include these in a config file if you like, I usually end up doing something like that for most of my applications.

$db =”foobase”; //Database Name
$dbuser =”someuser”; //Database Login
$dbpass =”thepassword”; //Database password
$dbhost =”localhost”; //Database Host Information

Lets break down the rest of this code line by line.

Here we define the function. We call it dbConnect and we are passing the variable $db into it.
function dbConnect($db) {

This line defines global variables and pulls in the host username and pass.
global $dbhost, $dbuser, $dbpass;

This sniplet will open the connection using the supplied host/login/pass/etc

$dbcnx =@mysql_connect($dbhost, $dbuser, $dbpass)
or die(”The site database appears to be down.”);

If there are any problems selecting the database we will get an error here
if ($db !=”" and !@mysql_select_db($db))
die(”The site database is unavailable”);

Return the connection
return $dbcnx;

This is a pretty simple connection script, a few ways to expand on it would be to use it as an include, and perhaps even use a config.php file to put the login information, then include that.