PHP中的foreach警告

时间:2017-07-27 16:57:43

标签: php mysql sql foreach

admin TABLE

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

我的代码

$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>";
}

所以,问题是如果结果中有多于一行它输出的确是我想要的,例如我说:

SELECT Username from admin;


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

但如果只有一行,则不会显示COLUMN名称并发出此警告

Select Username from admin where Username = 'JOHN';

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

1 个答案:

答案 0 :(得分:0)

偷偷摸摸的拼写错误/逻辑编码错误:你有一个花括号(括号)来搞砸一切。看看用于生成标题的foreach的结尾:

$sql = 'SELECT a.orderid, a.customername, a.email, b.orderid, b.menuitem FROM orders a, orderitems b WHERE a.orderid = b.orderid';

$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
            echo "<td>" . $row['customername'] . "</td>";
            echo "<td>" . $row['phone'] . "</td>";
            echo "<td>" . $row['email'] . "</td>";
            echo "<td>" . $row['menuitem'] . "</td>";
}

这应该是:

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

然后在最后移除假支撑。

这是有效的(只要至少有一行来获取heaedrs):

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