Skip to content Skip to sidebar Skip to footer

Trying To Get Property 'num_rows' Of Non-object

Could someone help me to correct this code? I keep getting this error:- Notice: Trying to get property 'num_rows' of non-object

Solution 1:

Change

if ($result->num_rows > 0) {

to

if (!empty($result) && $result->num_rows > 0) {

And then it will work.

EDIT: The reason it won't blow up is that first you are seeing if there are any results, first. If there are not, then it will not attempt to show them (this is where the error was occuring).

You really should replace

$sql =" SELECT * FROM img WHERE id = $test ";

with

$sql =" SELECT * FROM img WHERE id = ?";

and then use prepared statements. But that is another question.


Solution 2:

I'm not sure if you have declared your connection. Check this documentation

$conn = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $conn->query("SELECT ....")) {

    /* determine number of rows result set */
    if($result->num_rows > 0)
    {
       //....with the data stuff
    }


    /* close result set */
    $result->close();
}

/* close connection */
$conn->close();

Solution 3:

As suggested here [http://php.net/manual/it/mysqli.query.php], I would do it this way:

if ($result = $conn->query($sql)) {
    while($row = $result->fetch_assoc()) {
        // ...
    }
} 

If a query call fails it returns FALSE


Post a Comment for "Trying To Get Property 'num_rows' Of Non-object"