【问题标题】:How to user fetch_assoc() twice in a single php file? [duplicate]如何在一个 php 文件中使用 fetch_assoc() 两次? [复制]
【发布时间】:2020-09-08 08:27:18
【问题描述】:

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

【问题讨论】:

  • 只需查询文章表并获取结果。这是一个棘手的问题吗?
  • 或者您可能在第一个 fetch assoc 中想要另一个 fetch assoc,请不要这样做。改用连接

标签: php mysqli


【解决方案1】:

替换

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()) {
    // ...
}

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2017-03-04
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多