无法从结构化SQL语句中获取COUNT(*)结果

时间:2017-01-20 21:21:39

标签: php mysql

我一直在研究一个SQL语句,该语句检查数据库是否在24小时内从特定的 uuid 查看特定 qr_id 的反馈。原始代码按预期工作,但显然更安全,我想将代码更改为结构化SQL语句。

$uuid = "DB8962A3-BC7A-481F-9D7E-C1FC7F74E50E";
$qrid = "2147483647";
$query = sprintf("SELECT COUNT(*) FROM `feedback` WHERE uuid = '%s' AND qr_id = '%s' AND created_on > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))", mysql_real_escape_string($uuid), $qrid);
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];
if ($size > 0){
    echo 'Unable to leave feedback as user has left feedback for this employee within 24 hours.';
}else{
    echo 'User has not left feedback for this employee within 24 hours, continue.';
}

以上工作完全正常,如果计数大于0则会停止用户发布。这是我尝试将其转换为结构化SQL语句:

$stmt = $this->conn->prepare("SELECT COUNT(*) FROM `feedback` WHERE uuid = ? AND qr_id = ? AND created_on > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))");
    $stmt->bind_param('si', $uuid, $qrID);
    $result = $stmt->execute();
    $size = $result['COUNT(*)'];
    $stmt->close();
    if ($size = 0){
        // do post, return true
        return true;
    }else{
        return false;
        // do not post, return false
    }

我已经尝试打印结果值并且它始终为1,并且尝试回显$ size变量不会返回任何内容。

1 个答案:

答案 0 :(得分:0)

你需要获取结果,试试这个:

$stmt->bind_param('si', $uuid, $qrID);
$stmt->execute();
//here you bind result to variable $size
$stmt->bind_result($size);
$stmt->fetch() 
$stmt->close();
if ($size == 0){
    // do post, return true
    return true;
}else{
    return false;
    // do not post, return false
}