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
Keywords
Related Questions
- Are there any best practices for separating line numbers from code in a PHP forum?
- What are some common mistakes beginners make when trying to utilize the include_path in PHP functions, and how can they be addressed?
- What best practice should be followed when designing forms that require dynamic interaction based on user input?