I’m trying to use Json with my database using php5 but suffering from a weird result.
This database has four fields – ‘id’, ‘Title’, ‘Thread’, ‘date’ but the jason result looks like the following.
[
{
"0": "1",
"id": "1",
"1": "Title 1",
"Title": "Title 1",
"2": "Thread 1",
"Thread": "Thread 1",
"3": "2011-10-19",
"date": "2011-10-19"
},
{
"0": "2",
"id": "2",
"1": "Title 2",
"Title": "Title 2",
"2": "Thread 2",
"Thread": "Thread 2",
"3": "2011-10-03",
"date": "2011-10-03"
}
]
You can see there are duplicated information in the result. Where are they from??
I will attach the code I’ve written… Jason & PHP masters, please enlighten me :'(..
Thank you in advance.. I will try to solve it again as I wait for your help….
private static function queryAndFetch($tableName)
{
$query = "SELECT id, Title, Thread, date From $tableName";
$result = mysqli_query(self::$link, $query);
if(!($result))
{
echo "Error";
exit;
}
// $posts = mysqli_fetch_assoc(self::$result); - Working
self::$fetchedResult = array();
while($row = mysqli_fetch_array($result))
{
self::$fetchedResult[] = $row;
}
}
private static function encode()
{
//print_r(self::$fetchedResult);
//if($format == 'json') {
header('Content-type: application/json');
echo json_encode(self::$fetchedResult);
//}
//echo "hi".json_last_error();
}
}
mysqli_fetch_arrayreturns the result rows with both associative and enumerated keys. If you only want the associative array keys, then usemysqli_fetch_assoc.