PHP中的foreach警告

admin TABLE

+--------------+---------------+
| Username     | Password      |
+--------------+---------------+
| JOHN         | 123           |
| EDWARD       | 123           |
+--------------+---------------+

my code

$result = mysqli_query($connection, $query);
   echo" <table >";
     $row = mysqli_fetch_assoc($result);      
 echo "<tr>";
     foreach($row as $key => $val){   
       echo"<th>$key</th> ";
  echo "</tr>";
    ///////////////////////////////
  $result = mysqli_query($connection, $query);

      echo"<tr>";
    while($row = mysqli_fetch_assoc($result)){   
     foreach($row as $key => $val){   
       echo "<td>$val</td>";

     }
     echo "</tr>";

     }


    echo "</table>";
}

So, the problem is if there is more than 1 row in the result it outputs exactly what i want for e.g if i say:

SELECT Username from admin;


      +--------------+
      | Username     |
      +--------------+
      | JOHN         |
      | EDWARD       |
      +--------------+

But if there is only one row it does not show the COLUMN name and gives this warning

Select Username from admin where Username = 'JOHN';

    Warning: Invalid argument supplied for foreach()  on line 65
      +--------------+
      | JOHN         |
      +--------------+

Sneaky typo/logical coding error: you have a curly-bracket (brace) that's screwing everything up. Look at the end of the foreach used to generate the headings:

 foreach($row as $key => $val){   
   echo"<th>$key</th> ";

This should be:

  foreach($row as $key => $val)  
   echo"<th>$key</th> ";

And then remove the spurious brace at the very end.

This works (so long as there is at least 1 row to get the heaedrs):

$result = mysqli_query($connection, $query);

echo " <table >";

$row = mysqli_fetch_assoc($result);      

echo "<tr>";
foreach($row as $key => $val)
    echo"<th>$key</th> ";

echo "</tr>";

$result = mysqli_query($connection, $query);

echo"<tr>";
while($row = mysqli_fetch_assoc($result))
{   
    foreach($row as $key => $val)
    {   
        echo "<td>$val</td>";
    }
    echo "</tr>";

}

echo "</table>";