Reputation: 1807
Im new to PHP and trying to make a very simple api (good way too learn i think), why doesnt this work? When loading this page the output is: {"queryString":"SELECT id, Name FROM Food WHERE userID=1 ORDER BY Name"} and not the JSON-string that I want
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$response = $dbh->query("SELECT id, Name FROM Food WHERE userID=1 ORDER BY Name");
$responseJSON = json_encode($response);
header('Content-type: application/json');
echo "$responseJSON";
$dbh = null;
Nothing is wrong with the query because i get what i want when trying this:
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$response = $dbh->query("SELECT id, Name FROM Food WHERE userID=1 ORDER BY Name");
foreach ($response as $row)
{
print $row['Name'] . ' ';
}
$dbh = null;
outputs: Bacon Cheese chips
Upvotes: 2
Views: 5092
Reputation: 5668
$dbh->query retuns a PDOStatement object, not the rows. To add the rows to the json, call fetchAll on the object.
$response = $dbh->query("SELECT id, Name FROM Food WHERE userID=1 ORDER BY Name")->fetchAll();
You may also specify the fetch mode, e.g.
fetchAll(PDO::FETCH_ASSOC);
Upvotes: 10