Please consider the following:
$query = "SELECT legIDs FROM trip";
$result = mysql_query($query) or die("SELECT TRIPS ERROR: " . mysql_error());
while($row = mysql_fetch_assoc($result) or die("fetch error " . mysql_error())) {
echo "<div style=\"border: 1px solid blue;float:left;\">Trip: <div style=\"float:right;\">";
$legID = explode(",", $row['legIDs']);
foreach($legID as $leg) {
$query = "SELECT dep, arr FROM leg WHERE `Key` = " . $leg;
$result = mysql_query($query) or die("SELECT LEGS ERROR: " . mysql_error());
$row2 = mysql_fetch_assoc($result) or die("FILL ARRAY ERROR: " . mysql_error());
echo $row2['dep'] . " - " . $row2['arr'] . "<br />";
}
echo "</div></div>";
}
For some reason this only returns one result, even when there are several values returned from the WHILE() loop. The FOREACH() loop works on the one row that’s returned. Am I doing something wrong to only have this return one row? Performing the query contained in $result directly on the server returns several rows.
You’re using
$resulttwice in the inner and outer loops.. When the inner loop completes, $result will be an “empty” result set, so the outer loop will terminate. CHange the inner loop to$result2and things should be fine.However, since the inner loop is simply fetching more results based on what the outer loop produces, you should consider rewriting it as a joined query. It’s almost always more efficient to run a single “large result” query, than a long series of “small result” individual queries. You end up with fairly hefty overhead to parse/compile each of the inner queries.