PHP Database Configuration File Tutorial

For many web developers creating a database driven website is a standard requirement. This tutorial will show you how using a database configuration file can make your life a lot easier and keep your code a lot cleaner.

Why Bother?

The beauty of writting a config file is that once you have it, you can use it anywhere. Meaning you wont suffer from code repetition on your site. The real advantage comes from when you want to change the name or a password on a database, you can do this quickly and easily in one place.

Create Your Config File.

Lets go, create a new file and call it config.php this is what will house all our database specific information. The information required will resemble the following format.

<?php
	//website http structure
	$SITE = "http://".$_SERVER['HTTP_HOST'];
	$IMAGES = "images/";
	//connection string
	$con = mysql_connect('localhost','USERNAME', 'PASSWORD');
	//if connection fails
	if (!$con) {
		echo "cannot connect to database";
	} else {
		//select database
		$db = mysql_select_db('DATABASE_NAME', $con) or die("problem selecting database '$MYSQL[DATABASENAME]'");
	}
?>

In this file we are setting up a few global variables. We define the path of the website, the location of our images folder. Then comes the clever stuff, we define the connection to our database and store it against $con. Then below this we give display a message should our connection to the databse fail at any time otherwise we connect to the database we want. its as simple as that.

All we need do now is require this file on every page that needs to use a databse connection. This can be written like so.

<?php
require_once("http://www.yoursite.com/resources/config.php");
?>

By using the require_once() function we call in all the variables that are expressed the config.php file. This means that when we want to communicate with the database we can simply begin the sql expression, knowing the connection has already been created.

<?php
$sql = "SELECT * FROM yourTable";
?>

And thats all it takes, why not try it out on your own projects and see just how much time you can save youself.

  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • Google Bookmarks
  • email
  • Facebook
  • RSS
Theme forest

Talk to me