Search code examples
phpmysqlmysqlilamp

Why does mysqli_fetch_array() return array double the size?


I'm doing a very simple php statement such as

print_r($my_rec);
$row = mysqli_fetch_array($my_rec);
echo "\nP_Id " . $row['P_Id'] . ' Length ' . sizeof($row) . "\n";
$row = mysqli_fetch_array($my_rec);
echo "\nP_Id " . $row['P_Id'] . ' Length ' . sizeof($row) . "\n";

Now when print_r prints to the screen, it reports that there are only 16 fields/columns in each array. This is true. However when I fetch an array, it gives me double the fields. In other words the array is repeating itself which doesn't make sense. Example ...

I have in my database

 Col1  Col2
 "hi1" "bye1"

When I do

 $row = mysqli_fetch_array($my_rec);
 foreach($row as $x){
       echo $x . "\n";
 }

It will print

 hi1
 hi1
 by2
 by2

Why am I getting this behavior?


Solution

  • Because it also includes an array filled with columns's positions (i.e: 0, 1, 2, 3 and id, username, password, email). Both id and 0 hold the same data.

    If you only want the string indexes, you can use mysqli_fetch_assoc (http://php.net/mysqli_fetch_assoc)