JSON data not in correct format: fetching from mysql
<?php
require 'dbinfo.php';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $db->query("SELECT * FROM user_tracks");
$loc = $sth->fetchAll();
$locations = array_values($loc);
echo json_encode( array("user"=>( $locations )));
} catch (Exception $e) {
echo $e->getMessage();
}
?>
The code should return:
{"user":[{"id":"1","Latitude":"12.9555033333","Longitude":"80.2461883333","Time":"06:32:57","Date":"2012-03-13","Speed":"0","Course":"183.92"},{...},{....}]}
when it returns:
{"user":[{"id":"1","0":"1","Latitude":"12.9555033333","1":"12.9555033333","Longitude":"80.2461883333","2":"80.2461883333","Time":"06:32:57","3":"06:32:57","Date":"2012-03-13","4":"2012-03-13","Speed":"0","5":"0","Course":"183.92","6":"183.92"},{...},{....}]}
I'm not sure what's going on ... Where is the problem here?
Thanks in advance!
+3
source to share
1 answer
fetchAll () returns both (note the "fetch_style" argument comment / notes) and numeric data from the default query results. If you only want the string version you need to do
$loc = $sth->fetchAll( PDO::FETCH_CLASS );
+8
source to share