I have a statement, quite basic that pulls in from a database and displays the information. It works. However if I delete the entry in the database, the else statement should kick in a say that there are no results. However it does not. Can anyone see the problem?
This is the code, the bit i'm taking about is the if($result) {
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else {
$result = mysqli_query($con,"SELECT * FROM vacancies WHERE status ='0'");
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "<li><a href=\"current_vacancy?id=".$row['id']. "\">". $row['title'] ."</a> <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
}
Thanks
To implementing no result, you need to check number of rows you fetch by query with
mysqli_num_rows()
.In your case you checked for the $result variable this will store the status of the query execution, therefore it will always be true, since query will always execute even if it returns no rows.
To make it more natural way
and now you may use
$data
the way you tried to use $result:The result returned from
mysqli_query
is an object, not a row count. Usemysqli_num_rows($result)
to get the row count.By the way, be sure to call
mysqli_free_result($result)
at the end. Suggested outline: