drsw9390405 2019-07-07 16:56
浏览 140
已采纳

PHP错误 - mysqli_fetch_assoc返回Null [重复]

I am new to php and mysql. I am trying to read data from a table. Here's the code:

<?php
$conn = mysqli_connect("localhost", "root", "MyPass", "MyDB");
$sql = "SELECT Foo FROM MyTable";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if($row == null)
{
  echo'mysqli_fetch_assoc returned null';
}
else
{
  echo row['Foo'];
}
?>

And here's the table:

+---------+
|   Foo   |
+---------+
|       5 |
|       5 |
|       5 |
+---------+

`

Right now the code prints out "mysqli_fetch_assoc returned null", showing that something is wrong. Does anyone know what's causing the error? How can I fix it?

</div>
  • 写回答

2条回答 默认 最新

  • dongzha5934 2019-07-07 17:05
    关注

    I think you should mysqli_fetch_assoc inside while loop

    Like this.

    <?php
    $conn = mysqli_connect("localhost", "root", "MyPass", "MyDB");
    $sql = "SELECT Foo FROM MyTable";
    if ($result = mysqli_query($conn, $sql)) {
      while ($row = mysqli_fetch_assoc($result)) {
        if($row == null)
        {
          echo'mysqli_fetch_assoc returned null';
        }
        else
        {
          echo row['Foo'];
        }
      }
      mysqli_free_result($result);
    }
    
    mysqli_close($conn)
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据