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?
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_seekwill 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. 😛 Otherwise, each loop’s first iteration will spit out an empty row. Use
while (...) { }rather thando { } while (...).(Also be warned,
mysql_queryis 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.)