-1

I'm trying to show an array like this (show id_supplier and nama_supplier)

{"1":"PT Kesatu","2":"PT Kedua","3":"PT Ketiga","4":"PT Keempat"}

from supplier table. I've used the code below:

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier = $row;
}
echo json_encode($supplier);

but it's just showing me 1 record, and the results are like this

{"id_supplier":"5","nama_supplier":"PT Unggas Makmur"}
cbmeeks
  • 11,248
  • 22
  • 85
  • 136
  • 2
    Don't use `mysql_*` functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`pdo`](http://php.net/manual/en/book.pdo.php) instead. [And this is why you shouldn't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). – Rajdeep Paul Apr 25 '16 at 13:51

3 Answers3

1

It would be:

while($row = mysql_fetch_object($query)){
$supplier[] = $row; // not only $supplier - [] will automatically increment the index
}
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
1

Use [] array.

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier[] = $row;
}
echo json_encode($supplier);
RJParikh
  • 4,096
  • 1
  • 19
  • 36
0

You need to use [] array:

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier[] = $row; // not only $supplier ,but [] will increment, and get all the values
}
echo json_encode($supplier);
Nehal
  • 1,542
  • 4
  • 17
  • 30
  • @YvesLeBorg, I guess you didn't checked. Both answers were given almost at the same time, with nil time difference. You should have first watched it, before taking any action – Nehal Apr 26 '16 at 05:02
  • Unfortunately, i did 'checked' ... although noone can see it now, both other answers came togethers and yours 6 minutes later. – YvesLeBorg Apr 26 '16 at 10:26
  • @YvesLeBorg, it was just a difference of 2-3 min that I checked yesterday. But if you feel so I can't do anything – Nehal Apr 26 '16 at 12:05