我有兩張桌子。一個是文章列表,另一個是類別列表。在類別表中,我使用 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>
1 回答

桃花長相依
TA貢獻1860條經驗 獲得超8個贊
代替
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()) {
// ...
}
- 1 回答
- 0 關注
- 149 瀏覽
添加回答
舉報
0/150
提交
取消