newbie: free() after query()

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I am learning PHP5. I have a question concerning MySQL interface.
When I use query() function I free() result after using it. But sometimes
the code looks strange:

function agenciesInRegion($region_id)
        $result = $db->query("SELECT COUNT(*) FROM agencies WHERE is_active =
AND region_id = $region_id;");
        $r = $result[0];
        return $r;

Do I have to use temporal variable $r? Do I have to write such strange
commands because of free()? How would you write this function?
Please give me advice. Thanks a lot.

Re: newbie: free() after query()

Hello, wrote:
Quoted text here. Click to load it

When you choose to call free() after you performed the query you will
indeed need to store the result of the query into a temporary variable.
Otherwise you won't be able to use it. That speaks for itself.

Now, you can always perform the free() after you used the data. For example:

function foo_1($bar) {
   return $db->query("{YOUR MYSQL QUERY HERE}");

function foo_2($bar) {
   $foo = foo_1($bar);
   // Perform other stuff using $foo and free the result afterwards

Note that mysql_query() returns a reference to a result set. Since you
did not specify what kind of database abstraction layer you are using it
is possible your query function might return something else, but I would
assume that is very unlikely.

- Jensen

Re: newbie: free() after query() wrote:
Quoted text here. Click to load it

Yes, because if you call $result->free(), $result[0] is no longer available.

If I were looking for a single result, this is how I would write it.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Site Timeline