In the past I've had no issues using one simple:
$link = db_connect();
in a single file with multiple SQL commands like so:
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link)
or die("Couldn't execute query.");
Now any new file I create won't work without multiple/separate db_connects. For example:
$link = db_connect();
$link2 = db_connect();
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link2)
or die("Couldn't execute query.");
The old files with multiple mysql_queries referencing a single db_connect(); are still working fine. What could have changed?
Thanks.
Updated to include the db_connect(); function:
function db_connect($db="database", $host="localhost", $user="user", $p="password") {
$dbcnx = @mysql_connect($host, $user, $p);
if (!$dbcnx)
{
echo( "<p>Unable to connect to the database server at this time.</p>" );
exit();
}
$database = @mysql_select_db($db, $dbcnx);
if (!$db)
{
echo "<p>Unable to locate the database at this time.</p>";
exit();
}
return $dbcnx;
}
If you want to have $links separated, add true
as fourth mysql_connect()
parameter:
$dbcnx = @mysql_connect($host, $user, $p, true);
Additionally if you want to use different connections (different databases, users, passwords), you need to explicitly pass parameters to db_connect()
second time:
$link2 = db_connect('database2', 'whateverthehost', 'user2', 'andhispassword');
What you have posted looks fine unless you have something unset() ing $link, assigning it a value, or something else that is making $link no longer pointing to the database.