How do I echo an array with json?
My code does not seem to return JSON for $_GET['fruitVariety']
, any idea why?
My DB is correctly set up.
It's lik开发者_如何学Ce json_encode can only echo 1 array.
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE name = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
You're overriding the value you put in $rows
after the first query. You should do :
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
The brackets ([]
) are very important ! You can find more information about the proper syntax in the PHP documentation.
And actually, I think you only have the values for fruitVariety and not for fruitName ;)
精彩评论