【问题标题】:mysqli_fetch_assoc only returning one result, even though there is more [duplicate]mysqli_fetch_assoc 只返回一个结果,即使有更多 [重复]
【发布时间】:2020-10-18 14:13:47
【问题描述】:

当我在 PHPMyAdmin 中运行以下查询时,它返回了正确数量的结果。但是,当我尝试在 PHP 中回显结果时,它只输出一个结果,即使有多个结果也是如此。如何解决此问题以便显示每个结果?

$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt1, $sql1)) {
    header("Location:  note-premium.php?error=sql");
    exit();
}          
                    
else {
    mysqli_stmt_bind_param($stmt1, "s", $unique);
    mysqli_stmt_execute($stmt1);
    $result1 = mysqli_stmt_get_result($stmt1);
    while ($row1 = mysqli_fetch_assoc($result1)) {
        $names = $row1['userFirstname'];
    }
}
                
echo($names);

第二次尝试:我尝试创建一个数组。但这只是输出单词数组和错误消息“注意:数组到字符串的转换”。为什么?

$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt1, $sql1)) {
    header("Location:  note-premium.php?error=sql");
    exit();
}          

else {
    mysqli_stmt_bind_param($stmt1, "s", $unique);
    mysqli_stmt_execute($stmt1);
    $result1 = mysqli_stmt_get_result($stmt1);
    $column = array();
    while ($row1 = mysqli_fetch_assoc($result1)) {
        $column[] = $row1['userFirstname'];
    }
}

echo($column);

【问题讨论】:

标签: php mysql


【解决方案1】:

当您遍历结果并将“userFirstName”列的值存储在$names 中时,您将覆盖之前存储在其中的值。

您有两个选择 - 在循环结果时显示值,或者将值存储在数组中,然后再显示。

选项 1 - 在遍历结果时显示值:

while ($row1 = mysqli_fetch_assoc($result1)) {
   echo $row1['userFirstname'];
}

选项 2 - 将值存储在数组中并在循环后显示

$names = [];
while ($row1 = mysqli_fetch_assoc($result1)) {
   $names[] = $row1['userFirstname'];
}

foreach($names as $name) {
   echo '<p>'.$name.'</p>';
}

显然,您可以自定义如何循环遍历数组值并显示它们。我已将每个值包装在 &lt;p&gt; 标记中,以便它们显示在新行上。如果只想显示数组的未格式化内容,请使用print_r($names)

【讨论】:

  • 你为什么在一个地方使用while而在另一个地方使用foreach。你为什么前后矛盾?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 2012-09-09
  • 2022-12-13
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
相关资源
最近更新 更多