Mysqli查询出现额外空记录及foreach异常问题求助
Hey, let's troubleshoot that empty <li> tag and misbehaving foreach loop you're seeing with your MySQLi code!
The Root Cause
The issue comes from this line of code:
while ($zzmcat[] = $zmcat->fetch_array(MYSQLI_ASSOC)){}
When fetch_array() runs out of rows to return, it returns false. Your current code appends this false value directly to the $zzmcat array. So when you loop through the array later, the last element is an invalid false entry—this causes the empty <li> tag (since $zcatzn["cname"] will be undefined/empty) and throws off your inner loop logic.
Fix 1: Adjust the While Loop Logic
Rewrite your array population code to only add valid rows to the array:
$zzmcat = array(); // First capture the row, then check if it's valid before adding to the array while ($row = $zmcat->fetch_array(MYSQLI_ASSOC)) { $zzmcat[] = $row; }
This way, we only append data to $zzmcat when fetch_array() returns a valid associative array (not false).
Fix 2: Simplify with fetch_all()
If you're running PHP 5.3 or later, you can skip the manual while loop entirely and use fetch_all() to get all results in one go:
$zzmcat = $zmcat->fetch_all(MYSQLI_ASSOC);
This method directly returns an array of all rows, with no extra false element at the end—cleaner and less error-prone.
Bonus: Fix SQL Injection Risk
Your inner query uses string concatenation for the cat_id parameter (cat_id='".$zcatzn['cid']."'), which is a major SQL injection vulnerability. Replace it with a prepared statement to make your code secure:
// Prepare the inner query once, outside the loop $q = "SELECT id, ename FROM items WHERE view > 4 and status = 1 and cat_id = ?"; $stmt = $dba->prepare($q); foreach ($zzmcat as $zcatzn) { ?> <li class="category-list list-parent"><a href="#"><?php echo $zcatzn["cname"]; ?></a> <ul class="list-child"> <?php // Bind the category ID parameter (the "i" denotes an integer type) $stmt->bind_param("i", $zcatzn['cid']); $stmt->execute(); $result = $stmt->get_result(); while ($product = $result->fetch_array(MYSQLI_ASSOC)) { ?> <li class="category-list"><a href="#"> <?php echo $product['ename']; ?> </a></li> <?php } ?> </ul> </li> <?php } // Clean up the prepared statement $stmt->close();
These changes should eliminate the empty <li> tag and get your foreach loop working as expected, while also making your code more secure.
内容的提问来源于stack exchange,提问作者Fahad Almehaini

