Programmatically Deciding Which Database to Connect in PHPby: Amrit HallanProgrammatically 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:
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:
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. © 2008 NetVisits, Inc. All rights reserved. |