PHP – DB connections

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.

Example connection.inc.php:
[php]
$link = false;

function GetMyConnection()
{
global $link;
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”);
}
return $link;
}

function CleanUpDB()
{
global $link;
mysql_close($link);
}[/php]

Now, in your php scripts that require connections to your database, add:
[php]
require_once(“connection.inc.php”);
[/php]

Then, at the bottom (footer) of your script, add the following:
[php]
CleanUpDB();
[/php]

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”,
GetMyConnection() );
if( $result )

[/php]

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.
[php]
mysql_select_db(“other_database”,
GetMyConnection() );
[/php]

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.