0

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

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.