MySQLi Tutorial MySQLi References

mysqli $affected_rows Property



The mysqli::$affected_rows / mysqli_affected_rows() function returns the number of rows affected by the last SELECT, INSERT, UPDATE, REPLACE or DELETE query.

Syntax

//Object-oriented style
$mysqli->affected_rows;

//Procedural style
mysqli_affected_rows(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().

Return Value

Returns an integer which can be interpreted as follows:

  • An integer greater than zero indicates the number of rows affected or retrieved.
  • Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed.
  • -1 indicates that the query returned an error or this function called for an unbuffered SELECT query.
Note: If the number of affected rows is greater than the maximum int value (PHP_INT_MAX), the number of affected rows will be returned as a string.

Example: Object-oriented style

The example below shows the usage of mysqli::$affected_rows property.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_affected_rows) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//executing queries and displaying the affected rows
$mysqli->query("SELECT * FROM Employee");
echo "Affected rows (SELECT): ". $mysqli->affected_rows;

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

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

Affected rows (SELECT): 478
Affected rows (DELETE): 13

Example: Procedural style

The example below shows the usage of mysqli_affected_rows() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_affected_rows()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//executing queries and displaying the affected rows
mysqli_query($mysqli, "SELECT * FROM Employee");
echo "Affected rows (SELECT): ". mysqli_affected_rows($mysqli);

mysqli_query($mysqli, "DELETE FROM Employee WHERE Age>60");
echo "Affected rows (DELETE): ". mysqli_affected_rows($mysqli);

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

Affected rows (SELECT): 478
Affected rows (DELETE): 13

❮ MySQLi Functions Reference