我该如何计算PDO中所有已删除的行?

时间:2013-11-02 11:54:08

标签: php pdo count

$db->beginTransaction();
$del = $db->prepare('DELETE FROM hesabat_filter WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_istilik WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_nem WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_rek WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_soyuqluq WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_vent WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$db->commit();

$count = $del->rowCount();
echo $count;

虽然这个PDO工作正常,但我无法统计所有已删除的行。我想我应该为每个准备好的查询提供不同的变量然后收集变量。你的想法是什么?

2 个答案:

答案 0 :(得分:3)

  1. 如果您没有使用参数化查询并且没有重复使用查询,则不需要prepare()它。您可以按原样query()
  2. rowCount()仅返回上次查询的计数。由于这个原因,并且因为你一遍又一遍地覆盖$del,当然你只会得到最后一个查询的计数。您无法执行任何魔术,只需在每次查询后调用rowCount并计算总数。
  3. 但不是query + rowCount,而是PDO::exec,它已经完全符合您的要求:

      

    PDO::exec()在单个函数调用中执行SQL语句,返回受该语句影响的行数。

    $totals  = $db->exec('DELETE ...');
    $totals += $db->exec('DELETE ...');
    ...
    
    echo $totals;
    

答案 1 :(得分:1)

每次查询执行后递增计数器变量。试试这样

$count = 0;
$db->beginTransaction();
$del = $db->prepare('DELETE FROM hesabat_filter WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$count += $del->rowCount();
$del = $db->prepare('DELETE FROM hesabat_istilik WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$count += $del->rowCount();
$del = $db->prepare('DELETE FROM hesabat_nem WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$count += $del->rowCount();
$del = $db->prepare('DELETE FROM hesabat_rek WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$count += $del->rowCount();
$del = $db->prepare('DELETE FROM hesabat_soyuqluq WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$del = $db->prepare('DELETE FROM hesabat_vent WHERE model_id NOT IN (SELECT res_id FROM result)');
$del->execute();
$count += $del->rowCount();
$db->commit();

echo $count;