Reputation: 41
I am attempting to create two lists of records from a database in the same page like so:
<?php do { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } while ($row = mysql_fetch_assoc($result)); ?>
<?php do { ?>
<div>
<h1><?php echo $row['name']; ?></h1>
<p><?php echo $row['email']; ?></p>
</div>
<?php } while ($row = mysql_fetch_assoc($result)); ?>
While the first loop works fine, the second time around (creating the div) the do-while loop does not return any data. How should I go about fixing this?
Upvotes: 1
Views: 67
Reputation: 86506
Insert a mysql_data_seek($result, 0);
between the two loops to reset the result so you can read it again.
Be warned, if the query didn't return any rows, mysql_data_seek
will give you a warning. Check whether there were rows returned before using it.
Also be warned, your loops are backwards. You need to fetch, then display. :P Otherwise, each loop's first iteration will spit out an empty row. Use while (...) { }
rather than do { } while (...)
.
(Also be warned, mysql_query
is crap. Stop using it. Please. For all our sakes. The mysqli extension does the same thing, can work almost identically, and -- unlike mysql -- is actively maintained. Plus, when you finally get around to learning to use prepared statements (and you should learn to use prepared statements), mysqli has them.)
Upvotes: 1
Reputation: 28409
mysql_fetch_assoc returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead, i.e. removes the row as it gets it. A second iteration won't find rows.
This should work, maybe not the best way (I've used a db class forever).
$result2 = $result;
On iteration 2 use mysql_fetch_assoc($result2);
Upvotes: 0
Reputation: 175
Try to use different variable naming for the $result
, e.g $result1
and $result2
Upvotes: 0