You will find yourself making connections to databases frequently in PHP. Most commonly you will connect to MySQL, but this technique works with all of them.
First, create a connection.inc.php file, like shown.
$link = false;
if( $link === false )
$link = mysql_connect( “host”,
“user”, “password” )
or die(“Could not connect”);
mysql_select_db( “database_name” )
or die(“Could not select database”);
Now, in your php scripts that require connections to your database, add:
Then, at the bottom (footer) of your script, add the following:
Now, anywhere in your script that you need the link to your database, simply call GetMyConnection(). See example:[php]
$result mysql_query(“SELECT * FROM table”,
if( $result )
The biggest advantage to this technique is it keeps you from recoding the connection information for your database. It also allows you to use an easy to remember function to refer to in all your projects. For queries in functions, you would have no need to make sure the link variable is global or pass the link as an argument. You may even wish to make multiple functions for different databases, say GetODBCConnection(), and GetMyOtherConnection() 🙂
This technique is good for multiple MySQL databases too.
I hope you find making a global database connection include file as useful as I do.
Next post I will explain a couple of ways how to deal with those pesky magic quotes from POST and GET variables.