Gsingh Gsingh - 18 days ago 5
JSON Question

difficulty with Conversion of php to json file

I have been tiring to convert the PHP to JSON file but the JSON file generated is very different then normally occur.
The table is present below

rid rname mobile email address opentiming closetiming menuid type averagecost image
1 abc 9876543212 sbjaca@gmail.com fdsjdsfdnm 00:10:00 00:00:00 1 asian 120 http://gjsblog.esy.es/images/download.png
2 abcdefc 9876543212 ajit@gmail.com qwertym 00:00:03 00:00:04 2 chinese 120 http://gjsblog.esy.es/images/The_Table.png


The php file is present below

//retrieve.php
<?php
include("dbconfig.php");
$result = @mysql_query("select * from Restaurants ");

$response =array();

if(@mysql_num_rows($result)>0){

$response['Restaurants'] = array();

while($row=@mysql_fetch_array($result)){
array_push($response['Restaurants'], $row);
}
}

if($result){
$response['success']=1;
$response['message']="Records Retrieved sucessfully";
}else{
$response['success']=0;
$response['message']="Retrieval Failure";
}

echo json_encode($response);

?>


The JSON contains the data in the column twice, once before the column name and once after the column name. The JSON appears as

{
"Restaurants": [
{
"0": "1",
"rid": "1",
"1": "abc",
"rname": "abc",
"2": "9876543212",
"mobile": "9876543212",
"3": "sbjaca@gmail.com",
"email": "sbjaca@gmail.com",
"4": "fdsjdsfdnm",
"address": "fdsjdsfdnm",
"5": "00:10:00",
"opentiming": "00:10:00",
"6": "00:00:00",
"closetiming": "00:00:00",
"7": "1",
"menuid": "1",
"8": "asian",
"type": "asian",
"9": "120",
"averagecost": "120",
"10": "http:\/\/gjsblog.esy.es\/images\/download.png",
"image": "http:\/\/gjsblog.esy.es\/images\/download.png"
},
{
"0": "2",
"rid": "2",
"1": "abcdefc",
"rname": "abcdefc",
"2": "9876543212",
"mobile": "9876543212",
"3": "sbjaca@gmail.com",
"email": "sbjaca@gmail.com",
"4": "fdsjdsfdnm",
"address": "fdsjdsfdnm",
"5": "00:00:03",
"opentiming": "00:00:03",
"6": "00:00:04",
"closetiming": "00:00:04",
"7": "2",
"menuid": "2",
"8": "chinese",
"type": "chinese",
"9": "120",
"averagecost": "120",
"10": "http:\/\/gjsblog.esy.es\/images\/The_Table_(restaurant)_logo.png",
"image": "http:\/\/gjsblog.esy.es\/images\/The_Table_(restaurant)_logo.png"
}
],
"success": 1,
"message": "Records Retrieved sucessfully"
}

Answer

Change

while($row=@mysql_fetch_array($result))

To

while($row=@mysql_fetch_array($result, MYSQL_ASSOC))

Because if you just use the first statement, MYSQL_BOTH will be used as default, and make the result array like that.

Just a suggestion, you better use MySQLi or PDO_MySQL, because mysql_fetch_array has been deprecated in PHP 5.5.0 and removed in PHP 7.0.0

Comments