Becky Becky - 4 months ago 7
SQL Question

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?

Answer

Try:

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