Popa Gabriel Popa Gabriel - 20 days ago 5
HTML Question

MySQL Loop Through Column

I was working on a small project and I found that using the following code to loop through the column values is actually printing it twice.
For example:

admin
admin
user
user
...


And so on. Here is the code:

$sql = "SELECT username FROM users";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result))
{
foreach($row as $elem)
{
echo $elem . "<br/>";
}
}


Is the while loop affecting the foreach and is making it execute twice? Maybe a typo?

Answer

This happens because mysqli_fetch_array() fetches the row twice - once with the column as index, and once with a numbered index.

You could use mysqli_fetch_assoc() instead, or do mysqli_fetch_array(MYSQLI_ASSOC), which will only fetch it with the column as a key, rather than both.

Example, a var_dump() on the $row variable when using mysqli_fetch_array() could give

array(2) {
  [0]=>
  string(5) "admin"
  ["username "]=>
  string(5) "admin"
}
array(2) {
  [0]=>
  string(4) "user"
  ["username "]=>
  string(4) "user"
}

So as you can tell, it fetches the values twice, with different key-indexes. Doing as suggested above (mysqli_fetch_array(MYSQLI_ASSOC) or mysqli_fetch_assoc()) would only fetch the following

array(1) {
  ["username "]=>
  string(5) "admin"
}
array(1) {
  ["username "]=>
  string(4) "user"
}

Reference