Reputation: 4527
In order to output it in the grid, i must have a JSON syntax like the one below:
{
"data": [
{
"SupplierID": 1,
"CompanyName": "Exotic Liquids",
"ContactName": "Charlotte Cooper",
"ContactTitle": "Purchasing Manager",
"Address": "49 Gilbert St.",
"City": "London",
"Region": null,
"PostalCode": "EC1 4SD",
"Country": "UK",
"Phone": "(171) 555-2222",
"Fax": null,
"HomePage": null
},
{
"SupplierID": 2,
"CompanyName": "New Orleans Cajun Delights",
"ContactName": "Shelley Burke",
"ContactTitle": "Order Administrator",
"Address": "P.O. Box 78934",
"City": "New Orleans",
"Region": "LA",
"PostalCode": "70117",
"Country": "USA",
"Phone": "(100) 555-4822",
"Fax": null,
"HomePage": "#CAJUN.HTM#"
},....more data...
]
}
This is the code i am using:
mysql_connect('localhost','root','')or die(mysql_error());
mysql_select_db('testdb')or die(mysql_error());
$result = mysql_query("select * from city");
$data[]=array();
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
$jsondata=json_encode($rows);
echo $data[$jsondata];
}
But i am having certain errors.
Notice: Undefined index:
How Can i fix this?, thanks
Upvotes: 0
Views: 175
Reputation: 2178
You are encoding data too early. Normally you should construct entire multidimensional array and only then go about encoding it
mysql_select_db('testdb') or die(mysql_error());
$result = mysql_query("select * from city");
$data = array('data' => array());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data['data'][] = $row;
}
echo json_encode($data);
Upvotes: 1
Reputation: 6825
you need to add the encoded data to the array first
$data =array();
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
$jsondata=json_encode($rows);
$data[] = $jsondata;
}
now you can echo the whole thing (there might be an easier way)
echo explode( $data, ',' );
also, i think you might be able to encode the whole array at once.
Upvotes: 1