When operating databases using PHP, PDO is a recommended way to provide a unified, flexible and secure interface. Among them, the PDOStatement::rowCount() method is often used to obtain the number of rows affected by SQL operations, but it behaves slightly differently in different statement types (such as SELECT , INSERT , UPDATE , DELETE ). This article focuses on how to avoid common misunderstandings.
Usually we want to know how many lines are successfully inserted after performing the insert operation, such as:
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', 'Alice');
$stmt->bindValue(':email', '[email protected]');
$stmt->execute();
echo $stmt->rowCount(); // Expected output:1
In most cases, especially when using MySQL , rowCount() correctly returns the number of rows affected (usually 1) if a single INSERT statement is executed. But if you care about cross-database compatibility , you need to be careful.
For the following batch insert statements:
$sql = "INSERT INTO users (name, email) VALUES
('Bob', '[email protected]'),
('Charlie', '[email protected]')";
$stmt = $pdo->prepare($sql);
$stmt->execute();
echo $stmt->rowCount(); // exist MySQL Next usually returns 2
Although rowCount() is likely to return 2, this is not always supported by all database drivers , and in PostgreSQL, SQLite and other databases, this behavior may be unavailable or return 0.
For some databases, such as PostgreSQL, rowCount() returns values for statements of type INSERT .
So, if you want to use rowCount() safely to get the number of inserted rows in a cross-platform environment, make sure:
Use a database driver (such as MySQL) that supports this feature.
Use standard INSERT statements, without relying on ON DUPLICATE KEY or RETURNING clauses (unless the database explicitly supports them).
Here are some practical suggestions:
Confirm that the current environment is using MySQL or compatible drivers, and the return value of rowCount() is meaningful.
if ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql') {
echo "Insert successfully,Influence number of rows:" . $stmt->rowCount();
} else {
echo "No MySQL database,rowCount() The results may be inaccurate";
}
Most drivers support returning an affected number of rows of 1 for a single INSERT, which is recommended.
$pdo->beginTransaction();
$total = 0;
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$data = [
['name' => 'David', 'email' => '[email protected]'],
['name' => 'Eve', 'email' => '[email protected]']
];
foreach ($data as $row) {
$stmt->execute($row);
$total += $stmt->rowCount();
}
$pdo->commit();
echo "Insert in total $total OK";
Through a single insertion matching loop, you can ensure that rowCount() behaves consistently under each driver.
Misconception | illustrate |
---|---|
All databases believe that rowCount() is supported to return the number of inserted rows | In fact, PostgreSQL and SQLite may return 0 |
Trust rowCount() when inserting batch | May be inaccurate in non-MySQL environments |
Use rowCount() to determine whether the insertion is successful | It is better to use the Boolean return value of execute() to cooperate with the error handling mechanism |
If you only care about the inserted primary key ID (especially the autoincrement primary key), you can use:
$pdo->lastInsertId();
Note: Only suitable for inserting single rows and tables with auto-increment primary keys.
PDOStatement::rowCount() is a powerful tool that behaves slightly differently between different databases. When using it to get the number of rows affected by an INSERT INTO statement, it is recommended:
Priority is given to use in MySQL environment.
It is more secure to use transactions for batch insertion.
In multi-database scenarios, you should consider using database-specific RETURNING or other features to avoid relying on rowCount() .
To see more PDO practice examples, visit https://gitbox.net/docs/pdo .