dongruyan4948 2015-02-14 03:41
浏览 51
已采纳

PDO执行返回1但没有行受影响?

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;
}
  • 写回答

1条回答 默认 最新

  • doulai8405 2015-02-14 03:49
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能