0

I am trying to check if record exist in SQL and get a return -> True or False. It returns a notice: Notice: Trying to get property of non-object in.... if($result->num_rows > 0)

$connection = new mysqli('localhost', 'user', 'pass','db_name');
$query = "SELECT * FROM order WHERE telephone = '".$telephone."' AND order_status_id='0' ";

$result = $connection->query($query);
            if($result->num_rows > 0) {
                    echo 'found'; // The record(s) do exist
                }
            else{
                    echo 'not found'; // No record found
                }

    $connection->close();

4 Answers4

2

ORDER is a mysql reserved word. Using it as field name, table name or whatever except ORDER BY fieldname requires using backticks:

SELECT * FROM `order` WHERE ....

Otherwise, you will get a query error, which will turn $result into boolean false.

Also, your code is vulnerable to sql-injection. I advise you to use prepared statements.

Community
  • 1
  • 1
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • 1
    As a small tip to add, if you want to still use "order" as tablename but don't want to "escape" it each time, you can follow name convention and user plural : "orders" – Robin Choffardet Mar 30 '16 at 10:24
0

You are checking the rows of the query object. The query object does not contain the rows.

What you want to do is something like

$data = $result->fetch_array();
if ($data->num_rows > 0)
{
    //Rows exist
} else {
    //No rows exist
}
-2

It happens in case query do not injects object in your $result variable. You can make the following changes to proceed.

if(is_object($result) && $result->num_rows > 0) {
     echo 'found'; // The record(s) do exist
} else{
     echo 'not found'; // No record found
}

OR

if(!empty($result->num_rows)) {
         echo 'found'; // The record(s) do exist
    } else{
         echo 'not found'; // No record found
    }

Also keep the thing simple:

$query = "SELECT * FROM `order` WHERE telephone = '$telephone' AND order_status_id='0' ";
Ashwani Goyal
  • 616
  • 4
  • 18
-3
Use like this

 $sqlReq = " SELECT * FROM order WHERE telephone = '".$telephone."' AND order_status_id='0' ";

                $queryReq = mysql_query($sqlReq) or die(mysql_error());

                if(mysql_num_rows($queryReq) > 0)
                {
                    echo "found";
                 }else{
                     echo "not found";
                       }
Gorakh Yadav
  • 304
  • 5
  • 19