4

Possible Duplicate:
JSON encode MySQL results

I want to use php to create a json object like below. it will return a string as a response from result sql query.

{"Orders":[  
            {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},  
            {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}               
]
}

my code

<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv"); 
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" ); 

$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}

//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json)); 
mysql_close(); 
?>

But when use my code the result is not what I expected:

{"Orders":[ ["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"], ["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"] ]}

Can you help me?

Community
  • 1
  • 1
Takeshi
  • 221
  • 1
  • 4
  • 16

1 Answers1

14

You have to create an array for each row to specify the field name and value.

$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...);

Or use mysqli_fetch_assoc() function if the table column name is exactly what you want to use in your JSON:

$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
    $rows[] = $r;
}
$data = array('Orders' => $rows);
print json_encode($data);
Stanley
  • 5,057
  • 4
  • 34
  • 44
  • Does anyone know how to get all the columns in one line from each $row result? Without specifying each column name? – jamis0n Dec 19 '12 at 03:33
  • Use [mysql_fetch_assoc()](http://php.net/manual/en/function.mysql-fetch-assoc.php) function – Stanley Dec 19 '12 at 03:37
  • 3
    **No**, use [mysql ***i*** _fetch_assoc()](http://php.net/manual/en/mysqli-result.fetch-assoc.php) – dualed Dec 19 '12 at 03:47