Luigi Cerone Luigi Cerone - 3 months ago 8
JSON Question

MySQL table to JSON with strange output

I've this MySQL table:

TABLE `table1` (
`ID` int(11) NOT NULL,
`First` varchar(30) DEFAULT NULL,
`Second` varchar(30) DEFAULT NULL,
)


And this PHP code that is used for query the table and encode its contents into a JSON object:

<?php
/* Connection stuffs*/

$query = " SELECT * FROM table1;";
$results = mysql_query($query);
$stuff = array();
while($row = mysql_fetch_array($results))
array_push($stuff,$row);
$ja = json_encode($stuff);
echo $ja;
?>


Now, the code is working but I get a strange output (I'm only posting one row for question's readability but the others are the same) :

{
"0": "1",
"ID": "1",
"1": "ivh",
"First": "ivh",
"2": "gyt",
"Second": "gyt"
}


My question is: Why
echo $ja;
doesn't print this?

{
"ID": "1",
"First": "ivh",
"Second": "gyt"
}


Where do
"0","1","2"
come from? Furthermore the
"0"
's content is the same of
ID
, as well as
1-First
and
2-Second
. There kind of a relationship between the MySQL column number and the
$ja
contents.

I've also tried to use this query:

$query = " SELECT ID,First,Second FROM table1;";


But the results are the same. Could someone help me? Thanks!

Answer

Suggest you to use mysql_fetch_assoc() or mysql_fetch_array($results, MSSQL_ASSOC). It will return only columns instead of being duplicate

$query = " SELECT * FROM table1;";
$results = mysql_query($query);
$stuff = array();
while($row = mysql_fetch_array($results, MSSQL_ASSOC))
{
    array_push($stuff,$row);
}
$ja = json_encode($stuff);
echo $ja;