Reputation: 355
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.
Upvotes: 0
Views: 66
Reputation: 4483
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)
Upvotes: 1