What is the purpose of the function mysqli_affected_rows in PHP and how is it typically used?

The function mysqli_affected_rows in PHP is used to retrieve the number of rows affected by the last INSERT, UPDATE, REPLACE, or DELETE query executed. This function is useful for checking the success of database operations and for error handling. It returns the number of affected rows as an integer.

// Check the number of affected rows after executing an SQL query
$query = "UPDATE users SET name = 'John' WHERE id = 1";
mysqli_query($connection, $query);

if(mysqli_affected_rows($connection) > 0){
    echo "Update successful. Rows affected: " . mysqli_affected_rows($connection);
} else {
    echo "No rows were affected.";
}