Programmatically Deciding Which Database to Connect in PHP

by Amrit Hallan
Byteswoth.com
Thursday, 30th March 2006
Most of the time, while working with PHP and MySQL, we have to switch between the local PC and the remote server. To connect to a database, I often used the following function:

<?php

function connect_database()
{
$user_name="";
$pwd="";
$database_name="local_database_name";
$db_host="localhost";
$db=mysql_connect($db_host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
}

?>


After writing and debugging the code on my local machine, I would change the values of $user_name, $pwd and $database_name and upload the files to my client’s server. While I was developing the application (it was my first PHP project and I still maintain the program and the database for my client) there was no problem, as I would remember to change the values. But when, after the launch of the website, I routinely started altering the program (according to my clients interminably changing needs) I woud often forget to change the values, and consequently, render the website disfunctional. Then I changed the connect_database() function in the following manner:

<?php

function connect_database()
{
if($_SERVER[’HTTP_HOST’]=="localhost")
{
$location="h";
}
else
{
$location="s";
}

$db_host=$_SERVER[’HTTP_HOST’];

switch ($location)
{
case "s":
$user_name="remote_user_name";
$pwd="remote_password";
$database_name="remote_database_server_host";
break;
case "h":
$user_name="";
$pwd="";
$database_name="local_database_name";
break;
}

$db=mysql_connect($db_host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
}

?>


This time the function checks on its own whether it is the local host or the remote host and connects accordingly. You can choose the omit the line

$db_host=$_SERVER[’HTTP_HOST’];


and put

$db_host=”localhost”;


instead because most servers use localhost.

Options:
Printer Friendly
Email Friend

About The Author:

Amrit Hallan is a freelance web designer. For all web site development and web promotion needs, you can get in touch with him at amrit@bytesworth.com . For further details, visit http://www.bytesworth.com You can subscribe to his newsletter [BYTESWORTH REACHOUT] on Web Designing Tips & Tricks by sending a blank email at bytesworth-subscribe@topica.com.

Developer Categories



Developer Tutorials
ASP
CGI & Perl
CSS
Flash
HTML
Java
JavaScript
MySQL
PHP
Python
XML

Developer Documentation

Developer Tools



Search our Developer Tutorials
  The DevSyndicate Network