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.

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测