Skip to content
Advertisement

How to user fetch_assoc() twice in a single php file?

I have two table. One is an article list and the other one is a category list. In the category table, I have use fetch_assoc() to get the data from my DB and list in the table. But I want to fetch the article’s data in the article table. How do I use fetch_assoc() twice in the same php file?

<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>

articles 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>

Advertisement

Answer

Replace

while($row = $categoryResult->fetch_assoc()) {

with

foreach($categoryResult as $row)

It does the same but the foreach approach uses an automatic iterator that will always start from the beginning of the result set.

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

If for some reason, you must use while loop and the manual approach then you need to ensure that you always reset the internal pointer to the first records before starting your loop. However, manual looping is not recommended. It is easier to make more errors when doing this manually with while

$categoryResult->data_seek(0);
while($row = $categoryResult->fetch_assoc()) {
    // ...
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement