When using PHP's PDO (PHP Data Objects) to operate a database, developers often need to determine whether an SQL statement is executed successfully, especially when performing INSERT , UPDATE or DELETE operations. The PDOStatement::rowCount method provides a convenient way to check the number of affected rows to determine whether the database operation is valid.
rowCount() is a method in the PDOStatement class that returns the number of rows affected by the previous SQL statement. For statements of DELETE , INSERT , and UPDATE types, the driver depends on whether the SELECT statement is available (for example, MySQL's SELECT does not support accurate row return by default).
$affectedRows = $statement->rowCount();
where $statement is the return object after execution through $pdo->prepare() and $statement->execute() .
Let's take a look at a practical example, demonstrating how to use rowCount() to determine whether a UPDATE operation successfully updates any data.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=example_db", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE users SET email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':email', $newEmail);
$stmt->bindParam(':id', $userId);
$newEmail = "[email protected]";
$userId = 3;
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "User information updated successfully,Updated in total " . $stmt->rowCount() . " Record。";
} else {
echo "No records have been updated,It may be because the data has not changed or the userIDDoes not exist。";
}
} catch (PDOException $e) {
echo "Database operation failed: " . $e->getMessage();
}
?>
Limited support for SELECT : Although some database drivers support rowCount() after SELECT query, this is not cross-database compatible behavior. If you need an exact number of SELECT rows, consider using fetchAll() and counting the result array.
A row count of 0 does not equal failure : When the updated data is the same as the original data, SQL execution is successful but will not affect any rows, rowCount() returns 0. This situation should not be regarded as a failure, but rather as "no change."
Use in a transaction : Using rowCount() in a transaction will not be affected. You can decide whether to commit or roll back a transaction based on the return value.
PDOStatement::rowCount is a powerful tool for determining whether a database write operation takes effect, and is especially useful when it is necessary to provide feedback to users or perform logical judgments. However, developers need to understand how it behaves in different contexts to avoid misunderstanding the operational results.
By rationally using rowCount() , the robustness and user experience of PHP applications can be improved. If you encounter uncertain database operation effects during development, try to introduce rowCount() to improve the controllability and feedback capabilities of your code.