How can the mysqli_affected_rows function return a wrong value in PHP?

The mysqli_affected_rows function can return a wrong value in PHP if it is called before the query execution or if it is called on a SELECT statement. To ensure that mysqli_affected_rows returns the correct value, make sure to call it after executing an INSERT, UPDATE, DELETE, or REPLACE query.

// Incorrect usage that may return a wrong value
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
$affected_rows = mysqli_affected_rows($conn); // This will not return the correct value

// Correct way to use mysqli_affected_rows
$query = "UPDATE users SET name='John' WHERE id=1";
mysqli_query($conn, $query);
$affected_rows = mysqli_affected_rows($conn); // This will return the correct number of affected rows