Jroen
Jroen

Reputation: 472

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

Upvotes: 1

Views: 744

Answers (1)

krtek
krtek

Reputation: 26617

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

Upvotes: 5

Related Questions