Database connection script

No doubt you already use a database connection script. As a developer, you probably use different servers throughout the development process. When you move your application from one server to another, you maybe have to change the database connection script in order for the application to work on the new server.


If you forget to update your database connection script, and the client is sitting in front a monitor waiting to see their new web application, it can be quite embarrassing. So, use this script to include several servers in your database connection statements and all will be fine.

Database connection script

<?php

/*
# Database connection script Created by Jez D
# www.jez-d.co.uk
# Last updated Apr 2010
# This file is intended to be able to connect to your MySQL
# database no matter where it is situated.
# -----------------------------------------
# Insert your connection details for your different hosts into the
# switch statement below.
# You can add more hosts if you need to.
# --------------------------------------
# $server is the server address. Can be URI or IP
# $user is the username needed to connect
# $db is the name of the database
# $password is the password needed to connect
*/

$host = $_SERVER['HTTP_HOST'];

switch ($host)
{
case 'localhost':
$server = '';
$user = '';
$db = '';
$password = '';
break;

case 'domain of host 1':
$server = '';
$user = '';
$db = '';
$password = '';
break;

case 'domain of host2':
$server = '';
$user = '';
$db = '';
$password = '';
break;

default:
$server = '';
$user = '';
$db = '';
$password = '';
}

$link = mysql_connect($server, $user, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}

$selected = mysql_select_db($db,$link)
or die("Could not select database");

?>

I normally keep this database connection script in an include file.

1 Comment Posted in Web development
Tagged , , , , , , , ,

One Comment

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>