PHP
Affected rows with rowCount()
Learn the number of rows affected by UPDATE, DELETE and INSERT with rowCount().
What does rowCount() do?
rowCount() is called on a PDOStatement and returns the number of rows affected by the last INSERT, UPDATE or DELETE.
For example, after UPDATE users SET role = ? WHERE role = ?, $stmt->rowCount() tells you how many rows changed.
The result is useful to give feedback to the user or to verify the operation.
Verification pattern
When you run a bulk update, printing rowCount() confirms that the operation worked as expected.
For example, if you changed three users from 'editor' to 'admin' and rowCount() returns 3, you know that three rows actually changed.
If the result is 0, no row matched the WHERE clause; this helps catch missing IDs or typos.
Exercise Bulk update roles and print rowCount
In the skeleton below, use prepare and execute to change every user with role 'editor' to 'admin'. Then print the affected row count with rowCount().
Show example solution
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, role TEXT)");
$pdo->exec("INSERT INTO users (name, role) VALUES ('Alex', 'editor')");
$pdo->exec("INSERT INTO users (name, role) VALUES ('Sam', 'editor')");
$pdo->exec("INSERT INTO users (name, role) VALUES ('Dana', 'editor')");
$stmt = $pdo->prepare("UPDATE users SET role = ? WHERE role = ?");
$stmt->execute(['admin', 'editor']);
echo $stmt->rowCount() . "\n";
Test yourself
-
What does $stmt->rowCount() return after UPDATE?
- The total row count
- The number of affected rows
- The last inserted ID
- The error code
Show answer
The number of affected rows — rowCount() returns the number of affected rows after UPDATE, DELETE or INSERT.
-
Get the affected row count
$count = $stmt->____();
Show answer
$count = $stmt->rowCount();
-
Match operation to result
- INSERT
- New ID via lastInsertId()
- UPDATE
- Affected rows via rowCount()
- DELETE
- Deleted rows via rowCount()
- SELECT
- Rows via fetchAll()
Next lesson: Transaction management