mysqli affected_rows in PHP Example



The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.

mysqli affected_rows in PHP Example

The below PHP script return the number of affected rows from different queries:

<?php
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysqli = mysqli_connect($host, $username, $password, $db_name);

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

// Perform queries and print out affected rows
$mysqli -> query("SELECT * FROM Students");
echo "Affected rows: " . $mysqli -> affected_rows;

$mysqli -> query("DELETE FROM Students WHERE Age>32");
echo "Affected rows: " . $mysqli -> affected_rows;

$mysqli -> close();
?>
Output:
Affected rows: 6 Affected rows: -1

Comments