Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i am trying to fetch data from MySQL and show it in JSON format This is the partial PHP code

$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);

    while($row = $result->fetch_assoc()) {

    echo  json_encode($row),"<br/>";}

?> i am getting output as

{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"}
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}

but i need it as

food1:[
{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"},
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}
]

can anyone please guide me? i think what i am getting is in object format and i need output in array format i.e. with [ & ]. very new to this json and php.

share|improve this question

3 Answers 3

up vote 0 down vote accepted

You can incapsulate query results in array and after print it;

$sql = "SELECT item, cost, veg,     spicy_level FROM food1";
$result = $conn->query($sql);
$a = array();
while($row = $result->fetch_assoc()) {
  if($a['food1'] ==null)
     $a['food1'] = array():
  array_push($a['food1'],$row);}


  echo json_encode($a);
?></i>
share|improve this answer
    
it worked, thanks! –  saurabhC Mar 5 at 7:48

Don't call json_encode each time through the loop. Put all the rows into an array, and then encode that.

$food = array();
while ($row = $result->fetch_assoc()) {
    $food[] = $row;
}
echo json_encode(array('food1' => $food));
share|improve this answer

Your code should be :

$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);

$food['food1'] = array();

while($row = $result->fetch_assoc()) {
    $food['food1'][] = $row;    
}

echo  json_encode($food);
share|improve this answer
    
thanks, tried it bt it shows null –  saurabhC Mar 5 at 7:38
    
sorry... it was typo... updated the code... change the last line –  Gopakumar Gopalan Mar 5 at 7:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.