我正在尝试使用以下代码从我的数据库中创建一个变量($ 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行时,我哪里出错?
答案 0 :(得分:1)
要查看所有27个描述,您需要在循环中打印它们或将它们添加到数组中。当您运行循环并仅在循环结束后输出单个变量时,它将显示分配的最后一个值。
while ($row1 = $result1->fetch_assoc()) {
$order_description = $row1['order_description'];
echo $order_description."\n";
}
OR
while ($row1 = $result1->fetch_assoc()) {
$descriptions[]=$row1['order_description'];
}
print_r($descriptions);
注意强>
@RiggsFolly正确地指出你有一个额外的fetch_array调用被浪费,因此你永远不会看到第一行。摆脱它。
踢你代码的第三行
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
答案 1 :(得分:1)
使用以下方式使用group_concat并阅读注释
$sql_query1 = "SELECT group_concat(order_description separator ',') as order_description FROM single_user_orders WHERE username = '". $_SESSION['login_user'] ."'" ; // update thie query with group_concat
$result1 = mysqli_query($dbconfig, $sql_query1);
$count1 = mysqli_num_rows($result1);
$order_description = array();
if($count1 >= 1) {
while ($row1 = $result1->fetch_assoc()) {
$order_description = explode(',',$row1['order_description']); // explode the string
}
}
print_r($order_description);