I have my connection to MySQL in a function in a separate file.
That file is require_once'd in every php file that needs to connect to the database.
Sometimes I run queries directly from the page, other times I run them from yet another function.
It always worked for me from PHP 4.something to PHP 5.2.5
Configuration
<?php
// config.inc.php
define('CONFIG_DBSERVER', 'myserver');
define('CONFIG_DBUSER', 'username');
define('CONFIG_DBPASS', 'password');
define('CONFIG_DATA', 'database');
?>
Connection
<?php
// dbfx.inc.php
function db_connect($server, $user, $pass, $db) {
$con = mysql_connect($server, $user, $pass);
if ($con) {
if (!mysql_select_db($db)) return false;
}
return $con;
}
/* ... */
Use
<?php
require_once 'config.inc.php';
require_once 'dbfx.inc.php';
/* ... */
$con = db_connect(CONFIG_DBSERVER, CONFIG_DBUSER, CONFIG_DBPASS, CONFIG_DATA);
if (!$con) die('Error: ' . mysql_error());
/* ... */