← Back to Chapters

PHP MySQLi Affected Rows

? PHP MySQLi Affected Rows

? Quick Overview

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.

? Key Concepts

  • Used with INSERT, UPDATE, and DELETE queries
  • Helps verify whether a query actually changed data
  • Returns an integer value representing affected rows

⚙️ Syntax & Theory

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

? Code Example

Below is an example of how you can use mysqli_affected_rows() to check the number of affected rows after an update.

? View Code Example
<?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();
?>

? Live Output / Explanation

Expected Result

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.

? Interactive Understanding

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.

? Use Cases

  • Confirming successful UPDATE or DELETE operations
  • Logging database changes
  • Triggering actions only when data is modified
  • Validating bulk INSERT operations

✅ Tips & Best Practices

  • Always check the return value of mysqli_affected_rows() to confirm query impact
  • Use mysqli_insert_id() alongside affected rows after INSERT queries
  • Handle cases where affected rows return 0 to improve UX and error handling

? Try It Yourself

  • Modify the script to perform a DELETE query and display affected rows
  • Update multiple records and observe the affected rows count
  • Insert multiple rows in a single query and check the returned value
  • Add conditional logic when affected rows equal 0
  • Combine affected rows with transactions to verify changes before commit