In PHP, when performing database operations such as INSERT, UPDATE, or DELETE using MySQLi, you often need to know how many rows were affected by the operation. The mysqli_affected_rows() function returns the number of rows that were modified or affected by the last query.
The mysqli_affected_rows() function is particularly useful after executing an UPDATE, DELETE, or INSERT query to determine if any rows were impacted by the query.
mysqli → procedural & object-oriented
Below is an example of how you can use mysqli_affected_rows() to check the number of affected rows after an update.
<?php
// Database connection details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create MySQLi connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL UPDATE query
$sql = "UPDATE users SET email='john.doe@newdomain.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
// Fetch affected rows count
$affected_rows = $conn->affected_rows;
echo "$affected_rows record(s) updated successfully";
} else {
echo "Error: " . $conn->error;
}
// Close database connection
$conn->close();
?>
If the record with id = 1 exists and the email value changes, the output will display:
1 record(s) updated successfully
If no matching row exists, the affected rows value will be 0.
Think of mysqli_affected_rows() as a feedback counter. Every time you run an INSERT, UPDATE, or DELETE query, it immediately tells you how many rows were actually changed in the database.