This question already has an answer here:
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>
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)
?>
Use if condition like below:-
if(row['Foo'] == "")
{
echo'mysqli_fetch_assoc returned null';
}
else
{
echo row['Foo'];
}