-1

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?

  • 1
    **Error checking** but if you cannot be bothered, Add `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` to the top of your script. This will force any mysqli_ errors to generate an Exception that you can see on the browser as well as normal PHP errors. – RiggsFolly Jul 07 '19 at 17:11
  • This doesn't help! – Konstsntin Jul 09 '19 at 08:43

2 Answers2

0

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)
?>
kensong
  • 117
  • 3
0

Use if condition like below:-

if(row['Foo'] == "")
{
  echo'mysqli_fetch_assoc returned null';
}
else
{
  echo row['Foo'];
}
Mohit Kumar
  • 902
  • 2
  • 6
  • 18