我正在尝试使用以下代码使一个变量 ($order_description) 回显数据库中的 27 行:
$sql_query1 = "SELECT order_description FROM single_user_orders WHERE username = '". $_SESSION['login_user'] ."'";
$result1 = mysqli_query($dbconfig, $sql_query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$count1 = mysqli_num_rows($result1);
if($count1 >= 1) {
while ($row1 = $result1->fetch_assoc()) {
$order_description = $row1['order_description'];
}
}
虽然这段代码可以工作,但是当我 <?php echo $order_description; ?>
它返回 SELECT 语句的最后一行,而不是我应该看到的 27 行,我哪里出错了?
最佳答案
为了查看所有 27 个描述,您需要在循环中打印它们或将它们添加到数组中。当您运行循环并仅在循环结束后输出单个变量时,它将显示最后分配的值。
while ($row1 = $result1->fetch_assoc()) {
$order_description = $row1['order_description'];
echo $order_description."\n";
}
或者
while ($row1 = $result1->fetch_assoc()) {
$descriptions[]=$row1['order_description'];
}
print_r($descriptions);
注意
@RiggsFolly 正确地指出,您有一个额外的 fetch_array 调用,该调用会被浪费,因此您永远不会看到第一行。摆脱它。
踢掉代码的第三行
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
关于php - 使用 MySQLi 返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266154/