Hi,
I need to create a function that takes a query statement and return a result set, here is my code:
function getResultSet($query)
{
require_once('config.php');
require_once('opendb.php');
$result = mysql_query($query);
//require_once('closedb.php');
return $result;
}
As you can see, I have to comment out the closedb.php line to make it work, but that leaves the DB connection open, which is terrible, Right? How do I make the function work and the connection closed at the same time?
TIA
Create a function that return result set
Moderator: General Moderators
Re: Create a function that return result set
What is in closedb.php?
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Create a function that return result set
You are most likely freeing the result in the include. There is rarely a need to close the connection or free the result as this happens when the script ends.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: Create a function that return result set
Better yet, you should be passing your connection as an argument, as the connection stuff should be handled outside of that functions scope anyways.
Re: Create a function that return result set
You could try this:
function getResults($query){
$return = array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$return[] = $row;
}
return $return;
}
$stuff = getResults($query);
echo $stuff[0]['name];
echo $stuff[0]['dateofbirth'];
//the first key of the array will be each row number. $stuff[1] will be the second row returned from the query. $stuff[2] the third, etc...
But I agree with the others, the connection should be outside the function.
function getResults($query){
$return = array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$return[] = $row;
}
return $return;
}
$stuff = getResults($query);
echo $stuff[0]['name];
echo $stuff[0]['dateofbirth'];
//the first key of the array will be each row number. $stuff[1] will be the second row returned from the query. $stuff[2] the third, etc...
But I agree with the others, the connection should be outside the function.