PHP检查SQL中是否存在记录

时间:2016-03-30 10:12:09

标签: php mysql sql

我正在尝试检查SQL中是否存在记录并获得返回 - >对或错。 它返回一个通知: 注意:尝试获取非对象的属性.... 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 个答案:

答案 0 :(得分:2)

var left = chart.plotLeft, top = chart.plotTop; if(!chart.currentPoint) { chart.currentPoint = 0; } if (!chart.myPath) { chart.myPath = chart.renderer.path(['M', 0, 0]).attr({ stroke: 'red', 'stroke-width': 1 }).add(); } chart.myPath.attr({ d: [ 'M', chart.series[0].data[chart.currentPoint].plotX + left, chart.series[0].data[chart.currentPoint].plotY + top, 'L', chart.series[1].data[chart.currentPoint].plotX + left, chart.series[1].data[chart.currentPoint].plotY + top ] }); http://jsfiddle.net/hkju4mzk/。使用它作为字段名称,表名或除ORDER之外的任何内容都需要使用反引号:

ORDER BY fieldname

否则,您将收到一个查询错误,该错误会将SELECT * FROM `order` WHERE .... 变为布尔 false

此外,您的代码容易受到mysql reserved word的攻击。 我建议你使用准备好的陈述

答案 1 :(得分:0)

您正在检查查询对象的行。查询对象不包含行。

你想做的事情就像是

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

答案 2 :(得分:-2)

如果查询没有在$result变量中注入对象,则会发生这种情况。您可以进行以下更改以继续。

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

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

同时保持简单:

$query = "SELECT * FROM `order` WHERE telephone = '$telephone' AND order_status_id='0' ";

答案 3 :(得分:-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";
                       }