问题描述
我有两个桌子。一个是文章列表,另一个是类别列表。在类别表中,我使用fetch_assoc()从数据库中获取数据并在表中列出。但是我想在商品表中获取该商品的数据。如何在同一php文件中两次使用fetch_assoc()?
<table>
<caption class="table_title">Category Management</caption>
<thead>
<tr class="table_header">
<th>ID</th>
<th>Ttile</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while($row = $categoryResult->fetch_assoc()) {?>
<tr class="table_content">
<td><?php echo escape($row['id'])?></td>
<td><?php echo escape($row['title'])?></td>
<td><a href="./update_category.php?id=<?php echo escape($row['id'])?>">Edit</a></td>
<td><a href="./handle_delete_category.php?id=<?php echo escape($row['id'])?>">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
文章表
<tbody>
<?php while($row = $result->fetch_assoc()) {?>
<tr class="table_content">
<td></td>
<td></td>
<td></td>
<td><a href="./update.php">Edit</a></td>
<td><a href="./delete.php">Delete</a></td>
</tr>
<?php }?>
</tbody>
解决方法
替换
while($row = $categoryResult->fetch_assoc()) {
使用
foreach($categoryResult as $row)
它具有相同的功能,但是foreach
方法使用的自动迭代器始终从结果集的开头开始。
$categoryResult = $mysqli->query();
// OR
$categoryResult = $stmt->get_result();
// from start to end as associative array
foreach($categoryResult as $row) {
// ...
}
// again,from start to end as associative array
foreach($categoryResult as $row) {
// ...
}
如果由于某种原因必须使用while
循环和手动方法,则需要确保在开始循环之前始终将内部指针重置为第一个记录。但是,不建议手动循环。使用while
$categoryResult->data_seek(0);
while($row = $categoryResult->fetch_assoc()) {
// ...
}