Is there anything wrong with connecting and closing to a database by calling the function below with the mysql_query and mysql_fetch_array commands between the two
<?php
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
global $connection;
}
function close()
{
global $connection;
mysql_close($connection);
}
dbconnect();
$query = "Some SQL Statement";
$data = mysql_query($query, $connection); - L1
while (mysql_fetch_assoc($data))
{
//echo something
}
close();
?>
At present, I am getting an error saying that $connection at L1 needs to be a resource but is a BOOL. If I give a die statement there, the same is triggered. I have no idea what is wrong. Please spot any errors you can. I have to take a sabbatical from coding and I am back after a while.
Thanks & regards
Just put the global $connection; line in the beginning of the function instead and it should work. Using global keyword at the end of the function implies that you want to use the global variable $connection. But the thing you will be doing now is, assingning global variable $connection "the actual connection resourceID".
Not too sure but try closing it by using
everything else looks good
You must use the
global
keyword before assigning the$connection
variable. Otherwise, you declare a local$connection
inside the function and then call a reference to the yet non-existent global$connection
. In the other functions, that non-existent global is used.More readable would be to use the
$GLOBALS
array:Best of all would be to return
$connection
fromdbconnect()
and use that value in other functions:declare global $connection before calling mysql_connect()