affected_rows
In this article, we will focus on the mysqli_affected_rows() function in PHP, which is used to retrieve the number of rows affected by the previous MySQL
In this article, we will focus on the mysqli_affected_rows() function in PHP, which is used to retrieve the number of rows affected by the previous MySQL operation. We will provide you with an overview of the function, how it works, and examples of its use.
Introduction to the mysqli_affected_rows() function
The mysqli_affected_rows() function is a built-in function in PHP that is used to retrieve the number of rows affected by the previous MySQL operation. It is commonly used after executing an INSERT, UPDATE, or DELETE query.
How to use the mysqli_affected_rows() function
Using the mysqli_affected_rows() function is very simple. You just need to pass a valid MySQLi connection object as an argument. Here is an example:
How to use the mysqli_affected_rows() function?
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$mysqli->query("UPDATE users SET name='John' WHERE id=1");
echo "Rows updated: " . mysqli_affected_rows($mysqli);
$mysqli->close();
?>In this example, we create a new MySQLi object and execute an UPDATE query to update the name of a user with an ID of 1 to "John". We then call the mysqli_affected_rows() function to retrieve the number of rows affected by the query and output the result to the console.
Important note on SELECT queries
The mysqli_affected_rows() function does not return the number of rows for SELECT queries; it returns -1 in such cases. To count rows in a SELECT result, use mysqli_num_rows() on the result set. Additionally, SQL_CALC_FOUND_ROWS and FOUND_ROWS() are deprecated in MySQL 8.0.30+ and removed in 8.0.31+, so they should not be used in modern applications.
Conclusion
In conclusion, the mysqli_affected_rows() function is a powerful tool for retrieving the number of rows affected by INSERT, UPDATE, or DELETE operations in PHP. By understanding how to use the function correctly, you can effectively manage data changes in your MySQLi scripts.
Practice
What does the mysqli_affected_rows() function do in PHP?