Create a function that return result set

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mattshiao
Forum Newbie
Posts: 2
Joined: Sat Apr 11, 2009 5:59 am

Create a function that return result set

Post 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
Cirdan
Forum Contributor
Posts: 144
Joined: Sat Nov 01, 2008 3:20 pm

Re: Create a function that return result set

Post by Cirdan »

What is in closedb.php?
User avatar
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

Post 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.
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.
User avatar
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

Post 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.
User avatar
jkraft10
Forum Newbie
Posts: 10
Joined: Sun Feb 14, 2010 8:00 pm
Location: Fontana, CA

Re: Create a function that return result set

Post 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.
Post Reply