PHP:检查num行是否为零

时间:2017-12-07 10:49:29

标签: php sql mysqli

我正在尝试检查数据库返回的结果是否为零,但是我的代码

后总是降到零
if(isset($_POST['cust_id'])){
    $cust_id = $_POST['cust_id'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE cust_id=?");
    $stmt->bind_param('i', $cust_id);

}
else if(isset($_POST['receiverid'])) {
    $receiverid = $_POST['receiverid'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE receiverid=?");
    $stmt->bind_param('i', $receiverid);

}

if($stmt->execute()){
    $data  = array();
    if($stmt->num_rows ==0){
        $data[] = array(
           'message'=> 'No messages found',
           'status'=>0,
        );
    }
    else{
        $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) { 
            $data[] = array(
                'message'=> $row['message'],
                'time'=> $row['time'],
                'status'=> $row['status'],
            );
        }   
    }
}
echo json_encode( $data); 

请帮我弄清楚这种情况。谢谢

1 个答案:

答案 0 :(得分:1)

试试这个

执行查询并将数据导入result like $result=$stmt->execute() resultif() condition like if($result)if($result == 0)内进行比较,以便得出结果

$result=$stmt->execute();
if($result)
{  
    $data  = array();
    if($result ==0){
        $data[] = array(
               'message'=> 'No messages found',
               'status'=>0,
            );
    }
    else{

    $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) { 
            $data[] = array(
               'message'=> $row['message'],
               'time'=> $row['time'],
               'status'=> $row['status'],
            );
        }   
    }
}

$result = $stmt->get_result();之后写if($stmt->execute())并像这样比较if($result->num_rows ==0)