EternalHour
EternalHour

Reputation: 8621

PDO execute returns 1 but no row affected?

I am getting some weird behavior when using my PDO delete method and I'm hoping to get some answers why. For some reason, when I perform a delete (in this case the table is empty) the query returns 1. According to the documentation, it should be returning 0 if no rows are modified. Here is the code.

protected function dsn() {
    return 'mysql:host=' . $this->host . ';dbname=' . $this->db . ';charset=' . $this->charset;
}

//my PDO attribute options//
protected $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];
//I have separate connections for different queries with different permissions
depending on what I need to do//
protected function connectDelete() {
    $dsn = $this->dsn();
    $this->pdo = new PDO($dsn, $this->userDelete, $this->passDelete, $options);

    return $this->pdo;
}

function deleteQuery($query, $values = []) {

    $prepare = $this->connectDelete()->prepare($query);
    $result = $prepare->execute($values);

    return $result;
}

With all of the relevant code out of the way, here is the query.

require_once $root.'/classes/userDB.php';
$db = new userDB();

$query = "DELETE FROM table WHERE primaryKey = ? AND user_id = ?";
$values = [$pk_id,$user_id];
$result = $db->deleteQuery($query, $values);

echo $result;
returns 1

Am I doing something wrong?

EDIT #1 :
So I tried rowCount() to see what the outcome would be, and I got the following error.

Fatal error: Call to a member function rowCount() on a non-object...

So seems that the query is failing?

EDIT #2 :
Here is the new function that will return the affected rows.

function deleteQuery($query, $values = []) {

    $prepare = $this->connectDelete()->prepare($query);
    $prepare->execute($values);
    $result = $prepare->rowCount();

    return $result;
}

Upvotes: 1

Views: 2431

Answers (1)

deceze
deceze

Reputation: 522175

PDOStatement::execute

Returns TRUE on success or FALSE on failure.

true output as string turns into 1. This doesn't say anything about how many rows got deleted, just that the query succeeded (i.e. was syntactically correct and executed without errors). If you want to know how many rows were affected, you're looking for rowCount.

Upvotes: 6

Related Questions