mysql_fetch_array and loops

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
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

mysql_fetch_array and loops

Post by EricS »

I have a template with 15 fields that need to be filled. I query the database for the records I need. Now, I use a for loop to loop through 15 times because even if I don't have 15 records to use I still need to replace a field with a blank string if there is not a field for that record.

Code: Select all

for ($i = 1; $i < 16; $i++)
&#123;
    if ($row = mysql_fetch_array($result)) &#123;
        $object->insertRow('name' . $i, $row&#1111;'name']);
    &#125; else &#123;
        $object->insertRow('name' . $i, '');
    &#125;
&#125;
Now if there isn't another record, the if statement will fail and a blank is inserted. The question is, will calling mysql_fetch_array repeatedly after it has no more results slow the application down. Or is it better and faster to use the following code

Code: Select all

$bool = true;
for ($i = 1; $i < 16; $i++)
&#123;
    if ($bool) &#123;
        if ($row = mysql_fetch_array($result)) &#123;
            $object->insertRow('name' . $i, $row&#1111;'name']);
        &#125; else &#123;
            $object->insertRow('name' . $i, '');
            $bool = false;
        &#125;
    &#125; else &#123;
        $object->insertRow('name' . $i, "");
    &#125;
&#125;
Which is the more efficient code for this solution.

Thanks for everything members.
Eric Stewart
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

The second block of code (with the boolean check) would be better to use. Querying the database takes more resources than running an in-code statement. Granted, in your situation there would probably not be any noticable difference in performance, but it is a good practice to hit the database as little as possible.

Cheers
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

I would have used a different approach, I assume that you always want 15 rows..

Code: Select all

<?php

$rowcount = 15;

while ($rowcount && $row = mysql_fetch_assoc($r))   $object->insertRow('name' . $rowcount--, $row['name']);
while ($rowcount) $object->insertRow('name' . $rowcount--, ' ');
?>
Edit: Changed for mysql_fetch_array() to mysql_fetch_assoc, since your are using just the named associative anyway, save some resources where we can :) Actually, since you are quering just for a single column, using fetch_row and use $row[0] would be more efficient.. and make sure the query doesnt do SELECT * but picks the single column only.. And, while I am at it, if you need to be very efficient, don't use objects/oo, PHP is not very efficient with that at all
User avatar
BigE
Site Admin
Posts: 139
Joined: Fri Apr 19, 2002 9:49 am
Location: Missouri, USA
Contact:

Post by BigE »

Maybe I don't quite understand... but why not use MySQL's built in limit function?

Code: Select all

SELECT * FROM Table LIMIT 15;
That would return the 15 top rows on the table. Simple.
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

if there is less than 15 he wants to fill with blanks..
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

Just wondering

Post by EricS »

When I call mysql_query, mysql doesn't return all the results? It just passes an id so mysql will know what results your looking for when you run something like mysql_fetch_array. For some reason I thought mysql_query returned the actual results and php stored them temporarily. Then the mysql_fetch_array would return the results one record at a time from memory and not have to go back to mysql each time.

Just trying to learn the underlining operation of the language.

Also, I try to optimize my code whenever possible. But I'm building a library of objects to reuse on all my projects. I'm aware the PHP is a little slow with objects, but should that really keep me from using them, considering all the nice benefits that come with objects as well as their ease of use, say for instance I post the code to sites for other people to benefit from. What's everyones thought on this?

Thanks of the valuable help I always get here, thankfully I'm getting good enough not to bother everyone with the basic questions anymore.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

mysql_query supports both, buffered and unbuffered querries.
The optional result_mode parameter can be MYSQL_USE_RESULT and MYSQL_STORE_RESULT. It defaults to MYSQL_STORE_RESULT, so the result is buffered. See also mysql_unbuffered_query() for the counterpart of this behaviour.
So, by default the whole resultset is transfered to the client (and stored in memory) before your script fetches record by record with mysql_fetch_...
To keep both behaviours transparent PHP (and the underlying mysql-lib) always uses the resultID to retrieve the next data-line.
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

What exactly do you see as a benefit of using objects in thismanner?

The only benefit I see that people think of as useful is "namespacing", and easier implementation of multiple instances..

Reusability has little to do with it, just namespace functions and vars and group them logically...

I do not see any need of using OO in php unless you need to dynamically nest objects, like building DOM-tree's and such..

Code: Select all

<?php

  # Library: beer   (using namespace beer_  and one global var $beer)
  # (Untested) sample of multiple instance functionality without using objects

   function beer_new ($beername) {
      global $beer;  // Our data container
      if (!is_array($beer)) $beer = array(); // Create if not existent
      $id = $beer['idx_pointer']++;    // Keep track of our 'resource_id' or object_id or what to call it
      $beer[$id] = array (       // This is our vars
           'name' => $beername,
           'qty' => 0
      );
      return $id;   // return the resource_id / instance_id / object_id
   }

   function beer_destruct ($id) {
     global $beer;  // Our data container
     if (empty($beer[$id])) return false;  // nonexistent id
     unset ($beer[$id]);
     return true;
   }

   function beer_drink_one ($id) {
      global $beer;  // Our data container
      if (empty($beer[$id])) return false;  // nonexistent id
      if ($beer[$id]['qty'] > 1 )  return $beer[$id]['qty']--;   // if any left, return what was left  before taking one (always true)
      return 0;  // Return zero if nothing left..
   }

   function beer_buy ($id, $how_many) {
      global $beer;  // Our data container
      if (empty($beer[$id])) return false;  // nonexistent id
      $beer[$id]['qty'] += $how_many;
      return $beer[$id]['qty'];  // Return how much we got now
   }

   function beer_status ($id) {
      global $beer;  // Our data container
      if (empty($beer[$id])) return false;  // nonexistent id
      return $beer[$id]['qty'];
   }

   function beer_name ($id) {
      global $beer;  // Our data container
      if (empty($beer[$id])) return false;  // nonexistent id
      return $beer[$id]['name'];
   }


 # -----
 # Sample usage

  $mybeer = beer_new('Samuel Adams');

  beer_buy ($mybeer, 24);
  beer_drink($mybeer);
  echo 'I have '.beer_status($mybeer).' '.beer_name($mybeer).' left';

  beer_destruct($mybeer); // What a waste 

?>
Post Reply