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