Becky
Becky

Reputation: 5585

Getting all records json_encode

I'm trying to get all data from table 1 in json format.

$arr = array();
$sql = "SELECT * FROM table1 ORDER BY price DESC";
$statement = $connect->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();

foreach ($result as $val){
    $arr['id'] = $val['item'];
    $arr['price'] = $val['price'];
}
echo json_encode($arr);

Result:

{"id":"item00125","price":"112.35"}

The problem is that I get only one record. Why isn't the foreach(){ not sending all the records?

Upvotes: 1

Views: 219

Answers (4)

Vijay Makwana
Vijay Makwana

Reputation: 486

here your result variable get the all records but the problem is in the for each loop you are put the each value in position of ['id'] and ['price'] so every time for each loop put the value at that same position so means replace the value so you are getting the last value so I thing you have to put the every record in different different position like this:

$i = 0;
foreach ($result as $val)
{
    $arr[$i]['id'] = $val['item'];
    $arr[$i]['price'] = $val['price'];
    $i++; 
}   
echo json_encode($arr);

I hope it works fine

Upvotes: 1

Saty
Saty

Reputation: 22532

You got only one result because you override array key at every itration of loop

Just pass result set into json_encode Without using loop as

$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

Upvotes: 1

rad11
rad11

Reputation: 1561

Try:

foreach ($result as $val){
 $arr[] = array(
  "id" => $val['item'],
  "price" => val['price']
 );
}

Upvotes: 5

Indrasis Datta
Indrasis Datta

Reputation: 8618

That's because your array is being over-written every time.

Try this:

$i = 0;
foreach ($result as $val){
   $arr[$i]['id'] = $val['item'];
   $arr[$i]['price'] = $val['price'];
   $i++;
}   
echo json_encode($arr);

Upvotes: 2

Related Questions