Reputation: 1092
Can anyone help - this is driving me mad.
I am calling a mysql table and wish to display the results (or check the results with an if statement) more than once. But in this loop (see below) it only calls the table and its rows as an array in the first instance (of $i=1). This code will build 20 divs called Box but only populate the first one with table data. Why?
I think that I should be using a foreach loop within the outer loop (I have got this to work in wordPress with that btw) but can't figure out the syntax. Any help would be really appreciated.
$i=1;
while ($i <= 20)
{
echo "<div class=\"Box ".$i."\">";
echo $i;
echo "<br>";
while ($row = mysql_fetch_array($result))
{
echo $row['name'];
}
echo "</div>";
$i++;
}
Upvotes: 1
Views: 2156
Reputation: 2272
You can use mysql_data_seek to reset to pointer of the result, if you want to while through them all again, do:
mysql_data_seek ( $result, 0 );
Upvotes: 0
Reputation: 270609
If I understand, you are attempting to use the same result resource multiple times in a loop.
After looping over the result resource the first time, you need to rewind it back to its original position to be able to loop over it again. It can be rewound with mysql_data_seek($result, 0)
, but a better strategy is to load the whole thing into an array before your loops and then iterate the array in each loop:
// Load everything into the array `$results` first.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row['name'];
}
// Better an incremental for loop than a while with a counter
// for a situation where you know the endpoint values of $i
for ($i = 1; $i <= 20; $i++)
{
echo "<div class='Box $i'>";
echo $i;
echo "<br>";
// Inside your HTML, use the $results array
// rather than the MySQL resource
foreach ($results as $row)
{
echo $row['name'];
}
echo "</div>";
}
Upvotes: 1
Reputation: 31948
Maybe I don't understand well but you should try this :
$i=1;
while ($row = mysql_fetch_array($result) && $i <= 20) {
echo "<div class=\"Box ".$i."\">";
echo $i;
echo "<br>";
echo $row['name'];
echo "</div>";
$i++;
}
Because in your code, you do your "mysql loop" inside the first loop.
Upvotes: 1
Reputation: 162
Once mysql_fetch_array($result) is given, $result cannot be used again for fetch. So it won't work in a loop. Better store the result in an array and use it wherever needed.
Upvotes: 0
Reputation: 575
Try doing this,
$i=1;
while ($row = mysql_fetch_array($result))
{
echo "<div class=\"Box ".$i."\">";
echo $i;
echo "<br>";
echo $row['name'];
echo "</div>";
$i++;
}
Upvotes: 0