Jesse Schoff
Jesse Schoff

Reputation: 770

mysqli_fetch_assoc returns duplicate data

There are very similar questions here, but after a lot of searching and trying different things, I'm still stuck.

When using mysqli_fetch_assoc() to populate an array, each row is being added twice.

$query = "SELECT column FROM table WHERE year = 2012";
if ($result = mysqli_query($connect, $query)) {
  while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row["column"];
  }
echo implode(',', $data);
mysqli_free_result($result);
}

This is returning the following: 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10

I'm expecting 1,2,3,4,5,6,7,8,9,10

I added a few extra lines to do some debugging...

print_r($data) yields

Array ( 
[0] => 1 
[1] => 2 
[2] => 3 
[3] => 4 
[4] => 5 
[5] => 6 
[6] => 7 
[7] => 8 
[8] => 9 
[9] => 10 
[10] => 1 
[11] => 2 
[12] => 3 
[13] => 4 
[14] => 5 
[15] => 6 
[16] => 7 
[17] => 8 
[18] => 9 
[19] => 10 )

print_r($result); yields

mysqli_result Object 
( 
[current_field] => 0 
[field_count] => 1 
[lengths] => 
[num_rows] => 10 
[type] => 0 
)

If [num_rows] => 10, and i'm using mysqli_fetch_assoc() and not mysqli_fetch_array(), why is it adding the values to the array twice?

Upvotes: 1

Views: 2672

Answers (1)

AlecTMH
AlecTMH

Reputation: 2725

Probably you've already assigned some data to $data array. Try to empty it before while instruction:

$query = "SELECT column FROM table WHERE year = 2012";
if ($result = mysqli_query($connect, $query)) {
  $data = array();
  while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row["column"];
  }
echo implode(',', $data);
mysqli_free_result($result);
}

and see what it outputs.

I believe column is not a real column name otherwise you'll get an error.

Upvotes: 3

Related Questions