Current Location: Home> Latest Articles> How to get the deleted data quantity through PDOStatement::rowCount when deleting in batches

How to get the deleted data quantity through PDOStatement::rowCount when deleting in batches

gitbox 2025-05-20

When developing applications, we often need to batch delete records in the database. After the deletion operation is completed, it may be necessary to obtain the number of deleted records. PDO (PHP Data Objects) is one of the commonly used database access methods in PHP. It provides the PDOStatement::rowCount() method to obtain the number of affected rows. However, for batch deletion operations, there are some details to be paid attention to when using PDOStatement::rowCount() to get the number of deleted records.

1. Basic usage of PDOStatement::rowCount()

The PDOStatement::rowCount() method returns the number of rows affected by the most recently executed SQL statement. It is usually used to get the number of affected rows after a query operation (such as UPDATE or DELETE ).

 <?php
// Suppose we already have one PDO Example
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');

// Delete a record
$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();

// Get the number of deleted records
$deletedRows = $stmt->rowCount();
echo "Deleted {$deletedRows} Record";
?>

However, when deleting in batches, the rowCount() method may not return the number of deleted records as we expected.

2. Bulk deletion operation and rowCount() issues

When performing batch deletion, the number of rows returned by PDOStatement::rowCount() may not exactly match expectations. This is because some databases (such as MySQL) may optimize queries and return different number of affecting rows when performing batch deletion.

For example, in MySQL, DELETE operations sometimes affect zero rows because no records that meet the criteria may be found. Even for batch deletion operations, only the actual deleted records will be counted. At this point, rowCount() may return to zero, especially if there are no records that meet the criteria.

3. How to ensure that the number of deleted records is correctly obtained?

For batch deletion, to ensure the correct number of deleted records, you can consider the following methods:

Method 1: Query after using PDOStatement::rowCount()

One way is to perform the deletion operation first, and then query the number of records that have been deleted. After executing the DELETE statement, execute a SELECT COUNT() query to obtain the number of deleted records.

 <?php
// Suppose we want to delete all ages less than18Users
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE age < 18");
$stmt->execute();
$deletedCount = $stmt->fetchColumn();

// Perform deletion
$stmt = $pdo->prepare("DELETE FROM users WHERE age < 18");
$stmt->execute();

// Confirm the number of deleted records
echo "Deleted {$deletedCount} Record";
?>

Method 2: Use transactions to ensure consistency

In batch deletion operations, enabling a transaction ensures that the exact number of records is obtained before deleting the data. By performing DELETE operations and SELECT COUNT() queries in a transaction, data consistency between the two can be ensured.

 <?php
// Start a transaction
$pdo->beginTransaction();

try {
    // Get the number of records that meet the deletion criteria
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE age < 18");
    $stmt->execute();
    $deletedCount = $stmt->fetchColumn();

    // Perform deletion操作
    $stmt = $pdo->prepare("DELETE FROM users WHERE age < 18");
    $stmt->execute();

    // Submit transactions
    $pdo->commit();

    // Output number of deleted records
    echo "Deleted {$deletedCount} Record";
} catch (Exception $e) {
    // If an exception occurs,Roll back the transaction
    $pdo->rollBack();
    echo "Deletion failed: " . $e->getMessage();
}
?>

By using transactions, data inconsistencies between deletion operations and record count queries can be avoided.

Method 3: Use PDOStatement::rowCount() and the number of rows returned by the database

If you are using a database that supports returning row counts, rowCount() should return exactly the number of deleted records. If the database execution plan returns an error affecting row count, it may be necessary to supplement the data in other ways, such as using conditional queries, logs, etc.

4. Summary

When deleting data in batches, please pay attention to the following points when using PDOStatement::rowCount() to obtain the deleted records:

  • The number of rows returned by rowCount() is not necessarily completely accurate, especially for some optimized SQL operations.

  • To ensure that the exact number of delete records is obtained, the number of records that meet the criteria can be obtained by querying COUNT before performing the delete operation.

  • Using transactions ensures the atomicity of query and delete operations and avoids inconsistencies in intermediate data.

By combining these methods, we can more accurately obtain the number of records deleted in batch deletion operations and improve the stability and consistency of data operations.