sys_debug
sys_debug

Reputation: 4003

json showing duplicate output of mysql result

I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:

[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]

The code behind this is:

$dataArray = array();
while($r = mysql_fetch_array($result))
{
    $dataArray[] = $r;
}

print json_encode($dataArray, JSON_UNESCAPED_UNICODE);

Any idea?

Upvotes: 3

Views: 1318

Answers (4)

cihanblog
cihanblog

Reputation: 58

try this

//$dataArray = array();
while($r = mysql_fetch_array($result))
{
    $dataArray[] = $r;
}

print json_encode($dataArray, JSON_UNESCAPED_UNICODE);

I commented first line. Because you used like that $dataArray[].

Upvotes: 0

Mike Walston
Mike Walston

Reputation: 315

You're getting this because you can access the results either by name or by column index, but you're serializing the entire thing, so both ways of getting the data are showing up.

Upvotes: 0

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

You should set another fetch style. It now fetches all columns using both their 0 based index and their name.

This should work as expected:

$dataArray = array();
while($r = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $dataArray[] = $r;
}

print json_encode($dataArray, JSON_UNESCAPED_UNICODE);

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72981

This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.

Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().

while($r = mysql_fetch_assoc($result)) {
    $dataArray[] = $r;
}

Upvotes: 7

Related Questions