获取受多次删除影响的行数

时间:2015-05-20 01:05:43

标签: php mysql pdo

当我在PDO中删除多行时,如何计算受影响的行数?这是我用来删除多行的技术:

$selected = $_POST['checkbox'];
    $N = count($selected);
    for ($i = 0; $i < $N; $i++) {
        $result = $dbh->prepare('DELETE FROM users WHERE id= :id');
        $result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
        $result->execute();
    }

我尝试了这个,但它总是返回1:

$deleted = $result->rowCount();
    if ($deleted) {
        echo $deleted.' was deleted.';
    }

3 个答案:

答案 0 :(得分:2)

您正在运行循环,因此每次调用都会删除1;你需要添加一个计数器。

添加:

 $deleted += $result->rowCount();
循环内的

然后在外面:

if ($deleted) {
        echo $deleted.' was deleted.';
    }

答案 1 :(得分:2)

如果id字段是唯一的,那么该语句最多可能影响1行。但是,您正在准备一个新语句并在循环中执行它。您应该尝试累计删除的数量。

$deleted = 0;
for ($i = 0; $i < $N; $i++) {
    $result = $dbh->prepare('DELETE FROM users WHERE id= :id');
    $result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
    $result->execute();
    $deleted = $deleted + $result->rowCount();
}
echo $deleted.' was deleted.';

答案 2 :(得分:0)

这是一种在1次删除而不是运行多次删除的方法。 这样rowCount()将显示已删除的实际结果。

$selected = $_POST['checkbox'];

$placeholder = array();
$values = array();

foreach ($selected as $id) {
  $placeholder[] = ":".$id;
  $values[":".$id] = $id;
}


$sql = "Delete FROM users WHERE id IN (".implode(', ',$placeholder).") ";
$result = $dbh->prepare($sql);
$result->execute($values);

$deleted = $result->rowCount();

if ($deleted>0) {
    echo $deleted.' was deleted.';
}