3

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?

3
  • 2
    PSA: The mysql_* functions are deprecated in PHP 5.5. It is not recommended for writing new code as it will prevent you from upgrading in the future. Instead, use either MySQLi or PDO and be a better PHP Developer. Commented Jul 25, 2013 at 19:50
  • Sure thing. Will rewrite the php service soon to be OOP based. For now just testing for android sake Commented Jul 25, 2013 at 19:51
  • If you edit to mysqli_fetch_array in the question, I can up vote it... Commented Jul 25, 2013 at 19:54

4 Answers 4

7

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

aye dont know how it skipped me! I used assoc and now working fine. Thanks mate
0

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);

Comments

0

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.

Comments

0

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[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.