I am trying to retrieve data from MySQL using php but I am a bit new to php. I have a table like so
distance height time
25 70 17:50:24
12 69 17:30:24
15 55 17:10:24
And I hope to retain a JSON like in this format:
{
"data": true,
"time":[
"17:50:24",
"17:30:24",
"17:10:24"
],
"distance":[
25,
12,
15
],
"height":[
70,
69,
55
]
}
My php script is like this:
<?php
$db = mysqli_connect("127.0.0.1", "root", "pw", "test1");
$row=$db->prepare('SELECT * FROM table');
$row->execute();
$json_data=array();
$json_latdata=array();
$result = array();
$result1 = array();
foreach($row as $rec)//foreach loop
{
$json_array['distance']=$rec['distance'];
$json_array['height']=$rec['height'];
$json_array['time']=$rec['time'];
array_push($json_data,$json_array);
array_push($json_latdata,$json_array1);
}
$result = $json_data;
$result1 = $json_latdata;
echo json_encode(array($result,$result1));
?>
But the output is row format (with repeated headers) and not exactly in the JSON format I desire and its reading null:
[[{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null},
{"distance":null,"height":null,"time":null}],
[null,null,null,null,null,null,null,null,null,null]]
Thank you so much for the time!
$rec[...]indexes. This is case sensitive, so check the actual names in the table.$json_array1?SELECT *. If you only care about specific columns, name them explicitly.