如何在单个php文件中两次使用fetch_assoc?

问题描述

我有两个桌子。一个是文章列表,另一个是类别列表。在类别表中,我使用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()) {
    // ...
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...