当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Present count of deleted records

问题描述:

I have some simple code that deletes every record in a table smaller than a certain date. I am using PDO as db access method.

How can I see (and hence report to the user) how many records that were actually deleted in the database?

I was thinking transaction (count records to be deleted --> execute delete --> if everything was OK - present counted records to user), but there has to be an easier way, no?

It seems that execute only returns a boolean value that will only give me an indication of success.

$date = new DateTime('2014-06-22 12:00:00');

try{

$datestring = $date->format('Y-m-d H:i:s');

$dbh = getConnected($host,$user,$pass,$db);

$stmt = $dbh->prepare("DELETE FROM sometable WHERE date_and_time < '$datestring'");

$stmt->execute();

echo "$rd records deleted"; // where $rd = number of records deleted returned from the query

}

catch(PDOException $e)

{

echo 'Something went wrong!';

error_log($e->getMessage().PHP_EOL, 3, "errors.log");

}

$dbh -> connection = null;

网友答案:
$stmt->rowCount();

will give you number of rows affected

PDO rowcount

网友答案:

Try the affected_rows function:

printf("rows inserted: %d\n", $stmt->affected_rows);  
网友答案:

If that is mysqli being used (its not stated or clear), in your case, do $stmt->affected_rows

See http://php.net/manual/en/mysqli-stmt.affected-rows.php

分享给朋友:
您可能感兴趣的文章:
随机阅读: