PHP mysqli affected_rows Function

❮ PHP MySQLi Reference

Example - Object Oriented style

Return the number of affected rows from different queries:

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

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 Persons");
echo "Affected rows: " . $mysqli -> affected_rows;

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

$mysqli -> close();
?>

Look at example of procedural style at the bottom.


Definition and Usage

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


Syntax

Object oriented style:

$mysqli -> affected_rows

Procedural style:

mysqli_affected_rows(connection)

Parameter Values

Parameter Description
connection Required. Specifies the MySQL connection to use

Technical Details

Return Value: The number of rows affected. -1 indicates that the query returned an error
PHP Version: 5+

Example - Procedural style

Return the number of affected rows from different queries:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}

// Perform queries and print out affected rows
mysqli_query($con, "SELECT * FROM Persons");
echo "Affected rows: " . mysqli_affected_rows($con);

mysqli_query($con, "DELETE FROM Persons WHERE Age>32");
echo "Affected rows: " . mysqli_affected_rows($con);

mysqli_close($con);
?>


❮ PHP MySQLi Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.