mysqli statement not displaying else for no result

2019-09-07 04:43发布

问题:

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

回答1:

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.



回答2:

To make it more natural way

$data   = [];
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
while($row = mysqli_fetch_array($result)) {
    $data[] = $row;
}
?>

and now you may use $data the way you tried to use $result:

<?php foreach ($data as $row): ?>
    <li>
      <a href="current_vacancy?id=<?=$row['id']?>">
        <?=$row['title']?>
      </a>
      <img src="/images/rightarrow.png" alt="next">
    </li>
<?php endforeach ?>

<?php if(!$result): ?>
        There are currently no vacancies available
<? endif ?>


回答3:

The result returned from mysqli_query is an object, not a row count. Use mysqli_num_rows($result) to get the row count.

By the way, be sure to call mysqli_free_result($result) at the end. Suggested outline:

$result = mysqli_query(…);
if (!$result) {
    # Handle failure
} else {
    if (mysqli_num_rows($result) == 0) {
        # Handle no vacancies
    } else {
        # Normal case
    }
    mysqli_free_result($result);
}