//, PHP/Programmatically Deciding Which Database to Connect in PHP

Programmatically Deciding Which Database to Connect in PHP

Programmatically deciding which database to connect in PHP

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.

2010-05-25T23:05:17+00:00 October 17th, 2005|MySQL, PHP|0 Comments

About the Author:

Amrit Hallan is a freelance web developer. You can checkout his website at http://www.bytesworth.com. For more such articles join BYTESWORTH REACHOUT at http://www.bytesworth.com/br/default.asp or if you have a web dev related question then post it at http://www.business180.com/index.php

Leave A Comment