How can developers utilize object-oriented style for checking affected rows in Prepared Statements in PHP for more efficient code?
When using Prepared Statements in PHP to execute queries, developers can utilize an object-oriented style to efficiently check the affected rows after an operation. By using the `rowCount()` method provided by the PDOStatement object, developers can easily determine the number of rows affected by the query. This approach simplifies the code and improves readability.
// Create a PDO object
$pdo = new PDO($dsn, $username, $password);
// Prepare a statement
$stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
// Bind parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
// Execute the statement
$stmt->execute();
// Check the number of affected rows
$affectedRows = $stmt->rowCount();
echo "Number of affected rows: " . $affectedRows;