PHP fetch_assoc循环

时间:2018-12-17 21:46:52

标签: php mysql prepared-statement

我的查询选择了符合特定条件的所有行,但是为此使用fetch_assoc时遇到了问题,我只得到一行。

这是我的代码:

$stmt = $conn->prepare("SELECT filename, comment, action FROM files WHERE belongsto = ?");
$stmt->bind_param("s", $_POST['case_identifer']);
$stmt->execute();
$result = $stmt->get_result();
echo json_encode(array(($result->fetch_assoc())));
$stmt->close();
$conn->close();

我需要将fetch_assoc函数转换为循环,以便在JSON中获取所有结果,但是我不确定如何执行此操作,将不胜感激。

1 个答案:

答案 0 :(得分:1)

只需使用while循环将行写入数组,然后对其进行json_encode即可。因此,替换此行:

echo json_encode(array(($result->fetch_assoc())));

具有以下循环:

$output = array();
while ($row = $result->fetch_assoc()) {
    $output[] = $row;
}
echo json_encode($output);