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

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 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)
    ?>
    
    点赞 评论 复制链接分享
  • dst8922 dst8922 2019-07-07 17:06

    Use if condition like below:-

    if(row['Foo'] == "")
    {
      echo'mysqli_fetch_assoc returned null';
    }
    else
    {
      echo row['Foo'];
    }
    
    点赞 评论 复制链接分享

相关推荐