[SOLUTION] Warning: Mysqli_num_rows() Expects Parameter 1 to Be Mysqli_result

Mysqli_num_rows() expects parameter 1 to be mysqli_result is one of the most basic kinds of errors that occur in PHP while using MySQLi functions.

Warning: Mysqli_num_rows() Expects Parameter 1 to Be Mysqli_result

If you are getting this error, don’t panic; there is nothing to worry about because it is not an error actually. Basically, “mysqli_num_rows() expects parameter 1 to be mysqli_result” is a warning which occurs while fetching data using MySQLi functions.

When we use the mysqli_query() function with the SELECT query, it returns some resultant data from the database. We can use mysqli_fetch_array() or mysqli_fetch_assoc() function to fetch every resultant row.

Example

We have a table of students with two columns, “id” and “name.”

Warning: Mysqli_num_rows() Expects Parameter 1 to Be Mysqli_result

and we have a PHP code to fetch the student name as below.

<?php
    $conn = mysqli_connect("localhost", "USER_NAME", "PASSWORD", "DATABASE_NAME");
    $result = mysqli_query($conn,"SELECT * FROM `students` WHERE `id`=4");
    while($data = mysqli_fetch_assoc($result)){
        echo $data["name"];
    }
?>

If we want to find the name of the student with id ‘1’, it will display the output as below.

Output

Nick

The above PHP code is correct because there is a field with ‘id’ = 1

Now, if we try to fetch the name where ‘id’ = 4

Here the problem occurs of ‘Warning: Mysqli_num_rows() Expects Parameter 1 to Be Mysqli_result‘.

This warning might appear on your PHP page or in the error.log file; it depends on your working environment.

Solution

As we can understand from the above explanation that mysqli_query() returns no data because there is no data record exist with ‘id’ = 4 but still program proceeds and runs the next query of mysqli_fetch_assoc(), which expects at least one row in $result variable to fetch data and it prompts a warning.

To resolve that problem, we just have to check the number of results and only fetch data if there is at least 1 row in resultant data.

SOLVED CODE

<?php
    $conn = mysqli_connect("localhost", "USER_NAME", "PASSWORD", "DATABASE_NAME");
    $result = mysqli_query($conn,"SELECT * FROM `students` WHERE `id`=4");
    if(mysqli_num_rows($result) > 0){
        while($data = mysqli_fetch_assoc($result)){
            echo $data["name"];
        }
    }else{
         echo "No Records Found!";
    }
?>

Read Also: Mysqli_fetch_assoc vs Mysqli_fetch_array [With Example]

Conclusion

I hope now you can resolve the mentioned error in your amazing PHP project.

Happy Coding 🙂

One thought on “[SOLUTION] Warning: Mysqli_num_rows() Expects Parameter 1 to Be Mysqli_result

Leave a Reply

Your email address will not be published. Required fields are marked *