Ciprian
Ciprian

Reputation: 3226

mysqli - How to return false on 0 affected rows

The deleteItem method returns true even if the item isn't deleted. How can $mysqli->affected_rows be used in this particular case to check and return false if there are no changes to the database?

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;
}

Upvotes: 0

Views: 180

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157870

this is how it have to be.

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;
}

Upvotes: 1

Marc B
Marc B

Reputation: 360632

As per comment request, pseudo-ish code:

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
   }
}

Upvotes: 0

Related Questions