Page 1 of 1

Create a function that return result set

Posted: Sun Feb 14, 2010 10:19 am
by mattshiao
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

Re: Create a function that return result set

Posted: Sun Feb 14, 2010 11:37 am
by Cirdan
What is in closedb.php?

Re: Create a function that return result set

Posted: Sun Feb 14, 2010 12:30 pm
by AbraCadaver
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.

Re: Create a function that return result set

Posted: Sun Feb 14, 2010 9:42 pm
by John Cartwright
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

Posted: Sun Feb 14, 2010 10:12 pm
by jkraft10
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.