Re: Stupid newbie looping MySQL question
| From: | Rasmus Lerdorf | Date: | Mon, 08 Jan 2001 17:39:10 +0000 |
| Subject: | Re: Stupid newbie looping MySQL question | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-5712@lists.php.net to get a copy of this message | ||
> while($row=mysql_fetch_object($result)) {
> $fid = $row->id;
> $mynextquery ="SELECT id, datestamp, thread, subject, author FROM $row->table_name
> ORDER BY datestamp ASC LIMIT 0, 20";
> $result2 = mysql_query($mynextquery);
> if (!$row2 = mysql_fetch_object($result2)) { //this is line 27
> print ("<b>In <a
> href=\"/phorum/list.php?f=$fid\">$row->name</a></b>:</br>\n");
> print ("<font size=-1>Nothing new today.</font><br>\n");
> } else {
> print ("<b>In <a
> href=\"/phorum/list.php?f=$fid\">$row->name</a></b>:</br>\n");
> while($row2 = mysql_fetch_object($result2)) {
> print ("<font size=-1>" . date_format($s_row->datestamp, '%b
> %e, %Y') . ": <a
> href=\"/phorum/read.php?f=$fid&t=$s_row->thread&i=$s_row->id#i$s_row->id\">$s_row->subject</a>--$s_row->author</font><br>\n");
> }
> }
> }
One problem you have is that you are fetching $row2 twice. You fetch it
once to test if there is something there on line 27, if there is actually
something there you drop into the else clause where you do another fetch
instead of using the $row2 you just grabbed. This will cause your output
to always miss the first entry.
I would change the above to be:
while($row=mysql_fetch_object($result)) {
$fid = $row->id;
$tname = $row->table_name;
$name = $row->name;
$mynextquery ="SELECT id, datestamp, thread, subject, author FROM $tname ORDER BY datestamp
ASC LIMIT 0, 20";
$result2 = mysql_query($mynextquery);
if($result2) $row2 = mysql_fetch_object($result2);
else continue;
if (!$row2) {
print ("<b>In <a
href=\"/phorum/list.php?f=$fid\">$name</a></b>:</br>\n");
print ("<font size=-1>Nothing new today.</font><br>\n");
} else {
print ("<b>In <a
href=\"/phorum/list.php?f=$fid\">$name</a></b>:</br>\n");
do {
print ("<font size=-1>" . date_format($s_row->datestamp, '%b %e,
%Y') . ": <a
href=\"/phorum/read.php?f=$fid&t=$s_row->thread&i=$s_row->id#i$s_row->id\$>
} while($row2 = mysql_fetch_object($result2));
}
}
Not sure this fixes everything, but it should be really close. Note the
use of a do...while to make sure you don't miss the already fetched first
row.
-Rasmus