简体   繁体   English

如何从SQL请求接收多个结果

[英]How to receive multiple results from sql request

I have PHP code that queries to a mySQL database and returns some correct information in the form of an object array. 我有查询MySQL数据库的PHP代码,并以对象数组的形式返回一些正确的信息。

However, there should be more than one result, there are several rows in the database the match the query. 但是,应该有多个结果,数据库中有几行与查询匹配。

I have tried using a while loop, with a foreach nested inside, but I cannot get it to work. 我已经尝试过使用while循环,其中嵌套有一个foreach,但是我无法使其正常工作。

$stmt = $conn->prepare("SELECT * FROM planning WHERE intervenant = :id AND date = :date");
$result = $stmt->execute([':id' => $id, ':date' => $date]);

if ($stmt->rowCount() > 0) {
    $output = array();
    $output = $stmt->fetch(PDO::FETCH_ASSOC);
    echo json_encode($output);
} else {
    $errors = "No data found for this date";
    echo json_encode($errors);
}


WHILE LOOP THAT I TRIED TO USE WITHIN IF PART OF CODE ABOVE

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    foreach ($row as $key => $output) {
    echo json_encode($output);
}

So I would like the code to return several arrays, each containing the data queried. 因此,我希望代码返回几个数组,每个数组包含查询的数据。

Using the code I have that works, I get just one object array returned. 使用有效的代码,我只会返回一个对象数组。

Trying the while loop, I get "Uncaught Error: Call to a member function fetch() on boolean". 尝试while循环时,出现“未捕获的错误:在布尔值上调用成员函数fetch()”。

Please, any help is appreciated. 请任何帮助表示赞赏。

Instead of: 代替:

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    foreach ($row as $key => $output) {
    echo json_encode($output);
}

Try: 尝试:

$output = $result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM