mysqli - 如何在0个受影响的行上返回false

时间:2015-07-09 18:46:00

标签: php mysql mysqli

即使未删除该项,deleteItem方法也会返回true。如果没有对数据库进行任何更改,如何在此特定情况下使用$mysqli->affected_rows来检查并返回false?

public function deleteItem($item_id)
{
    $userItemIDS = array();

    $userItemIDS = $this->helperClass->userItemIDS();

    $q = $this->db->mysqli->prepare("DELETE i, s FROM items i
    LEFT JOIN save_list s
        ON i.id = s.item_id
        WHERE i.id = ? AND s.item_id = ?
    AND
        NOT EXISTS (SELECT id FROM pending_wins WHERE item_id = ?)
    AND
        NOT EXISTS (SELECT id FROM bids WHERE item_id = ?)");

    if( $q != false && in_array($item_id, $userItemIDS) )
    {
        $q->bind_param("iiii", $item_id, $item_id, $item_id, $item_id);
        $q->execute();
        $q->close();
        return true;
    }
        return false;
}

2 个答案:

答案 0 :(得分:1)

这就是必须的。

public function deleteItem($item_id)
{
    $userItemIDS = $this->helperClass->userItemIDS();
    if( !in_array($item_id, $userItemIDS) )
    {
        return FALSE;
    }
    $sql = "...";
    $q = $this->db->mysqli->prepare($sql);
    $q->bind_param("iiii", $item_id, $item_id, $item_id, $item_id);
    $q->execute();
    return (bool)$this->db->mysqli->affected_rows;
}

答案 1 :(得分:0)

根据评论请求,伪代码:

if (ok to run query) {
   $q = "...build/prepare/bind query...";
   if ($q->execute() === false) {
       return false; // query failed
   } else {
       return $q->rowCount(); // return number of rows affected
   }
}