if your case I would write some sort of wrapper function in a separate file like-so:
function DBconnect() {
static $db_link = null;
if (!is_resource($db_link)) {
$db_link = @mysql_connect('...');
if (!$db_link) {
trigger_error('Could not connect to database', E_USER_ERROR);
}
}
return $db_link;
}
require_once() the script where you put this function, and use it like so:
require_once('db.php');
// fetches current database connect or creates a new one
// if it does not exist
$db_link = DBconnect();
... work with the connection here
The above code is very rough, but you should get the idea.
You could go one further and create a class to store all your connection information, such as your username, password, host, port, etc. as well as provide database-agnostic functions so in the future you can switch out MySQL with PostgreSQL (or PostgreSQL to MySQL or whatever) and you only have to replace out the method code instead of hunting down all the mysql or psgl function calls in your code.
Or even just make a function that returns the information as an array:
function DBgetConnectionInfo() {
return array('host' => 'localhost',
'port' => 3306,
'username' => 'myuser',
'password' => 'mypass');
}
Instead of rolling your own, you can look at solutions such as Pear:😃B:
http://vulcanonet.com/soft/index.php?pack=pear_tut