开发者

How do I echo an array with json?

开发者 https://www.devze.com 2023-04-01 20:26 出处:网络
My code does not seem to return JSON for $_GET[\'fruitVariety\'], any idea why? My DB is correctly set up.

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 ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消