我正在尝试循环检索 MySQL 数据。但只有第一个显示数据。其他的都是空的。这就是现在的工作方式 -
这是我的代码:
<?php
for ($i = 1; $i <= $quantity; $i++) {
echo'
<tr>
<!-- <td><input class="case" type="checkbox"/></td> -->
<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off" placeholder="Enter IMEI number"></td>
<td><select name="brand[]" class="form-control autocomplete_txt">';
while ($row = mysqli_fetch_array($result_brand)) {
echo '<option value="' . $row['brand'] . '">' . $row['brand'] . '</option>';
}
echo' </select> </td> <td><select name="model[]" class="form-control autocomplete_txt" >';
if (mysqli_num_rows($result_model) > 0) {
// output data of each row
while ($row_model = mysqli_fetch_assoc($result_model)) {
echo ' <option value="' . $row_model['model'] . '">' . $row_model['model'] . '</option>';
}
}
echo'
</select>
</td>
<td><input type="text" data-type="productName" name="brand[]" id="itemName_1" class="form-control autocomplete_txt" autocomplete="off" placeholder="Brand"></td>
<td><input type="text" data-type="productName" name="model[]" id="itemName_2" class="form-control autocomplete_txt" autocomplete="off" placeholder="Model"></td>
<td><input type="number" name="price[]" id="price_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" value="1" name="quantity[]" id="quantity_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" disabled></td>
<!-- <td><input type="number" name="total[]" id="total_1" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" disabled></td> -->
</tr>
';
}
?>
我不确定到底是什么问题。
最佳答案
问题是 while
循环运行一次后,mysqli
结果的光标指向结果的末尾。
您必须调用mysqli_data_seek在 for
循环开始时将光标重置到第一个数据集:
for($i=1; $i<=$quantity; $i++) {
mysqli_data_seek($result_brand, 0);
mysqli_data_seek($result_model, 0);
...
另一个解决方案是在 for
循环之前运行一次 while
循环,并将结果存储在数组中,以便您使用数组而不是使用 mysqli_fetch_array
在 for
循环中。
关于php - php 中的嵌套循环的工作方式与预期不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32394238/