Re: (correction) nesting mySQL queries/while statements

From: Date: Sat, 06 Jan 2001 04:46:52 +0000
Subject: Re: (correction) nesting mySQL queries/while statements
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-33017@lists.php.net to get a copy of this message
> $result = mysql_query("SELECT DISTINCT lastname FROM content WHERE > flavor=$flavorsku",$db); > > while ($myrow = mysql_fetch_array($result)) { > > printf ("<b>%s</b><br> \n<ul>", > $myrow["lastname"]); > > $lastname = ($myrow["lastname"]); > > $result = mysql_query("SELECT * FROM content WHERE > lastname=$lastname",$db); > > while ($myrow = mysql_fetch_array($result)) { You can't use $result to store two different values at the same time... Since you are trying to keep track of multiple result sets, you probably should name the variables something more distinctive than $result -- Like $lastname_result for the first one and $data_result. Also -- If the list of lastnames is going to get fairly large -- to the point where you'll be doing 20 or 30 (or more) queries inside that loop... That's going to get pretty excessive pretty fast. Sending an extra query or two to the database is okay, but sending a whole bunch is a Bad Idea (tm) for performance. Here would be a much better way for this particular case: $query = "select * from content order by flavor, lastname"; $content = mysql_query($query) or die(mysql_error()); $last_flavor = 'An extremely unlikely value for flavor, eh?'; $last_lastname = 'An extremely unlikely value for lastname as well'; while ($row = mysql_fetch_array($content)){ $flavor = $row['flavor']; $lastname = $row['lastname']; if ($flavor != $last_flavor){ echo "<B>$flavor<BR>\n"; $last_flavor = $flavor; $last_lastname = 'You *could* have the same lastname starting off the new flavor as we ended with on the last flavor, so force a new lastname to print by using an extremly unlikely lastname here'; } if ($lastname != $last_lastname){ echo " &nbsp; $lastname<BR>\n"; $last_lastname = $lastname; } echo " &nbsp; &nbsp; &nbsp; ", $row['blah'], $row['foo'], $fow['bar'], ...; } As a general rule -- If there's a way to make SQL do more of the sorting/collating/searching/filtering work and let PHP just rip through it, you're better off. There are times when coming up with the SQL to do what you need is just too tricky, and you fall back on nesting your queries like you had it: Just be sure that you rig things so you only have a certain number of them per page and provide forward/back navigation or something to avoid sending 50 queries to the database.

« previous php.general (#33017) next »