I'm trying to move my database query code (currently at each place I call the database) out to a common function in an include file which is loaded at the top of every PHP page. The function contained in the include is simple as follows:
function dbquery ($query)
{
@$db = mysql_pconnect('localhost','root','password');
if (!$db)
{
echo 'Connection failed.';
exit;
}
mysql_select_db('dbname');
$result = mysql_query($query);
return $result;
}
However, when it is called from code coming after the include in the main page:
dbquery ('SELECT countryid, countryname FROM country;');
for($i = 0; $i < mysql_num_rows($result); $i++)
{
echo mysql_result($result, $i, "countryid");
}
I get the following errors:
Notice: Undefined variable: result in ...(page)
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in ... (page)
All other variables appear to be available between the include and the main page, just not results from the database.
I've tried both with, and without the 'return $result;' entry in the function, but neither works.
Can anyone help me out? Is this a scope issue, or something peculiar to database recordsets?
I figure this must be a common enough thing to try to do, but can't find reference to it anywhere on the web.
Many thanks in advance.
Rob.
function dbquery ($query)
{
@$db = mysql_pconnect('localhost','root','password');
if (!$db)
{
echo 'Connection failed.';
exit;
}
mysql_select_db('dbname');
$result = mysql_query($query);
return $result;
}
However, when it is called from code coming after the include in the main page:
dbquery ('SELECT countryid, countryname FROM country;');
for($i = 0; $i < mysql_num_rows($result); $i++)
{
echo mysql_result($result, $i, "countryid");
}
I get the following errors:
Notice: Undefined variable: result in ...(page)
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in ... (page)
All other variables appear to be available between the include and the main page, just not results from the database.
I've tried both with, and without the 'return $result;' entry in the function, but neither works.
Can anyone help me out? Is this a scope issue, or something peculiar to database recordsets?
I figure this must be a common enough thing to try to do, but can't find reference to it anywhere on the web.
Many thanks in advance.
Rob.