📅  最后修改于: 2023-12-03 15:18:20.670000             🧑  作者: Mango
The PDO
class in PHP provides an interface to connect and interact with databases in a consistent manner. The rowCount
method is a part of PDOStatement
class, which is used to retrieve the number of rows affected or returned by a database operation.
int PDOStatement::rowCount()
The rowCount
method returns the number of rows affected by the last executed SQL statement. It can be used for various types of database operations like INSERT, UPDATE, DELETE, or SELECT statements.
When executing a SELECT statement, rowCount
returns the number of rows returned by the SELECT statement. For other statements like INSERT, UPDATE, or DELETE, it returns the number of rows affected by the statement.
Here is an example that demonstrates the usage of rowCount
method:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$sql = "UPDATE users SET status = 1 WHERE id = ?";
$statement = $pdo->prepare($sql);
$statement->bindParam(1, $id);
$statement->execute();
$rowCount = $statement->rowCount();
echo "Number of rows affected: " . $rowCount;
?>
In the above example, we connect to a MySQL database using PDO and prepare an UPDATE statement to update the status of a user based on their ID. After executing the statement, we use rowCount
to get the number of affected rows.
rowCount
may not return the correct number of rows for SELECT statements on certain databases, as it depends on driver implementation.rowCount
may return 0
for SELECT statements, in which case it's recommended to use fetch
or fetchAll
to determine the number of returned rows.For more information, refer to the PHP manual on PDOStatement::rowCount.