View Full Version : nested while loop problem

06-29-2007, 08:57 PM
My problem is that in the <em>Also found in:</em> section it is only displaying the results for the first entry and not the rest
any idea what would cause this to happen?

$result = $db->query("SELECT * FROM business_detail");
$result2 = $db->query("SELECT * FROM business_type");

while($row = $db->fetchArray($result)) {
<? if($row['b_image']) { ?><img src="../images/thumb_b/<? echo $row['b_image']; ?>" /><br /><? } ?>
<strong>Title:</strong> <? echo $row['b_title']; ?> <br />
<strong>Address:</strong> <? echo $row['b_address1']; ?><br /><? if($row['b_address2']) { echo $row['b_address2']."<br />"; } ?>
<strong>Phone:</strong> <? echo $row['b_phone']; ?><br />
<strong>Fax:</strong> <? if($row['b_fax'] == "") { echo "n/a"; } else { echo $row['b_fax']; } ?><br />
<strong>Email:</strong> <? echo $row['b_email']; ?><br />
<strong>Website:</strong> <? if($row['b_weburl'] == "n/a") { echo $row['b_weburl']; } else {?><a href="<? echo $row['b_weburl']; ?>"><? echo $row['b_weburl']; ?><a><? } ?><br />
<strong>Description:</strong><br /> <? echo $row['b_desc']; ?><br />
<em>Also found in:</em> <br />
$types = preg_split("/[\-,]+/", $row['b_types']);
while($row2 = $db->fetchArray($result2)) {
//$types = str_replace("-", " ", $row['b_types']);

if(in_array($row2['t_short'], $types)) { echo $row2['t_name']."<br /> "; }

06-29-2007, 09:27 PM
fetch_array() is like a file read, it fetches one row at a time, repositioning the "pointer" at the next row. You rip through all the rows the first time, until the pointer gets to the end of the results set, then bails out of the loop. You don't ever reset the "pointer", so the pointer remains at the end of the results and that loop never gets executed again.

Since (apparently) you want the same data to be displayed for every business detail row, you can simply fetch the query results into an array once and then use the array with a foreach() to loop the echo statement.

06-29-2007, 09:37 PM
ok i got the foreach to spit out the values of the array but i still need to do the while($row2 = $db->fetchArray($result2)) because i need to see if $value matches any of the entries in the database.
any ideas?

06-29-2007, 10:04 PM
Yeah you do need to still do the fetch loop, just not inside the first loop. Do it outside the first loop. Within the first loop, loop through the array that you build.

06-29-2007, 10:18 PM
You can also use the mysql_data_seek( resource result, int row_number ) function to reset the pointer back to the first row of the result set.