Robert Ross
Robert Ross

Reputation: 1189

Turning a db result set into a valid json with php

In my php I am running a simple query which returns a resultset(0 or many) from the database I have.

Currently on the fronted the rersult looks like this :

name: Smoothie description: Banana Smothie name: Phad Thai description: Noodles with shrimps name: Noodles description: Noodles with noodles.

The string can also look like this, aka name: Smoothie description: Banana Smothie or with more entries, like in the example above.

The code below gives me this :

[{"name":"Smoothie","description":"Banana Smothie"}][{"name":"Phad Thai","description":"Noodles with shrimps"}]

What I'd like to have is, so it can be just one json object :

 [{"name":"Smoothie","description":"Banana Smothie"},{"name":"Phad Thai","description":"Noodles with shrimps"}]

This is my php :

    <?php
 include_once 'db/dbconnect.php';
 $input = json_decode(stripcslashes($_POST['data']));

 for ($i=0; $i < count($input); $i++) {
     $stmt=$con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
     $stmt->bind_param("s", $input[$i]);
     $stmt->execute();
     $stmt->store_result();
     $stmt->bind_result($db_recipe_name, $db_recipe_description);

     $rslt = array();
     $arr = 0;
     while ($stmt->fetch()) {
         $rslt[$arr] = array('name' => $db_recipe_name, 'description' => $db_recipe_description);
         $arr++;
     }
     $jsonRslt = json_encode($rslt);
     echo $jsonRslt;
 }
 ?>

Can someone help me making this to a one json object?

Upvotes: 1

Views: 40

Answers (3)

Zeeshan S.
Zeeshan S.

Reputation: 2091

Inside the for loop, the $rslt array is re-initialized every time for each i which is why you are getting multiple JSON objects instead of a single one.

You need to initialize the $rslt outside the for loop and encode it into JSON after the for loop.

<?php
 include_once 'db/dbconnect.php';
 $input = json_decode(stripcslashes($_POST['data']));

 // Initialize array here
 $rslt = array();
 $arr = 0;

 for ($i=0; $i < count($input); $i++) {
     $stmt=$con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
     $stmt->bind_param("s", $input[$i]);
     $stmt->execute();
     $stmt->store_result();
     $stmt->bind_result($db_recipe_name, $db_recipe_description);

     while ($stmt->fetch()) {
         $rslt[$arr] = array('name' => $db_recipe_name, 'description' => $db_recipe_description);
         $arr++;
     }
 }

 // encode into JSON
 $jsonRslt = json_encode($rslt);
 echo $jsonRslt;
 ?>

Upvotes: 1

M. Eriksson
M. Eriksson

Reputation: 13645

Instead of creating new arrays that you json_encode and echo inside the loop, create one before the loop and add each object to it.

Example:

<?php
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));

// Create an array before the loop
$json = [];

for ($i=0; $i < count($input); $i++) {
    $stmt=$con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
    $stmt->bind_param("s", $input[$i]);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($db_recipe_name, $db_recipe_description);

    while ($stmt->fetch()) {
        // Add each element to the main array
        $json[] = array('name' => $db_recipe_name, 'description' => $db_recipe_description);
    }
}

// json_encode and echo the main array
echo json_encode($json);
?>

Upvotes: 1

Create php array inside for loop. Don't json encode / echo inside loop. Echo only final resulting php array out side outer for loop. Also, set response header to json. - sorry for typo. Answered from mobile.

Upvotes: 0

Related Questions