PHP错误-mysqli_fetch_assoc返回Null

时间:2019-07-07 16:56:37

标签: php mysql

我是php和mysql的新手。我正在尝试从表中读取数据。这是代码:

<?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'];
}
?>

这是桌子:

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

`

现在,代码打印出“ mysqli_fetch_assoc返回null”,表明出了点问题。有谁知道是什么原因引起的错误?我该如何解决?

2 个答案:

答案 0 :(得分:0)

我认为您应该在while循环内使用mysqli_fetch_assoc

喜欢这个。

<?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 :(得分:0)

在以下情况下使用:-

if(row['Foo'] == "")
{
  echo'mysqli_fetch_assoc returned null';
}
else
{
  echo row['Foo'];
}