Search code examples
phpmysqlmysqli

mysqli_fetch_array gives me duplicate fields in the output


I have this SQL command:

SELECT Username FROM Family WHERE Parent = ? LIMIT 10

When I run that command on my phpMyAdmin and substitute some valid value instead of $Username, I have this in result:

+----------+
| Username |
+----------+
| johndoe  |
+----------+

But when I write a function like this:

function userParent($Username)
{
  global $con;
  $Result = mysqli_execute_query($con, "SELECT Username FROM Family WHERE Parent = ? LIMIT 10", [$Username]);
  $Result = mysqli_fetch_array($Result);
  return $Result;   
}

I get this array in return:

Array ( [0] => johndoe [Username] => johndoe ) 

So when I call that function in my script using a foreach loop like this:

$Parent = userParent('james');

foreach ($Parent as $value){
  echo $value . '<br>';
}

I always have duplicate 'johndoe' in the output.

I believe this duplicate data is caused by mysqli_fetch_array. How can I remove this duplicate data from the output?


Solution

  • mysqli_fetch_array() returns both an associative and numeric based array of your MySQL results. Use mysqli_fetch_assoc() instead.