Web Development

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.

About the author

Written by Amrit Hallan.

Amrit Hallan is a freelance web developer. You can follow the link below to checkout his website.

If you found this post useful you may also want to check these out:

  1. How To Backup Your MySQL Database With PHP
  2. Storing Images in a Database
  3. Adding records to a MySQL database using PHP
  4. Publishing Newsletter Using PHP & MySQL – 2
  5. Publishing Newsletters Using PHP & MySQL – 3
  6. Using PHP Objects to Access Your Database Tables (Part 1)