简体   繁体   中英

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.

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.

$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".

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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