mysqli::$affected_rows

mysqli_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli::$affected_rows -- mysqli_affected_rowsDevuelve el número de filas afectadas por la última operación MySQL

Descripción

Estilo orientado a objetos

Estilo por procedimientos

mysqli_affected_rows(mysqli $mysql): int|string

Devuelve el número de filas afectadas por la última consulta INSERT, UPDATE, REPLACE o DELETE asociada al argumento link.

Funciona como mysqli_num_rows() para las consultas SELECT.

Parámetros

link

Sólo estilo por procediminetos: Un identificador de enlace devuelto por mysqli_connect() o mysqli_init()

Valores devueltos

Un entero mayor que cero indica el número de filas afectadas o recuperadas. Cero indica que ningún registro fue modificado por una consulta del tipo UPDATE, ninguna fila coincide con la cláusula WHERE en la consulta o que ninguna consulta fue ejecutada. -1 indica que la consulta devolvió un error o que mysqli_affected_rows() fue llamado sobre una consulta SELECT no almacenada en búfer.

Nota:

Si el número de filas afectadas es mayor que el valor máximo (PHP_INT_MAX) que puede tomar un entero, el número de filas afectadas será devuelto como un string.

Ejemplos

Ejemplo #1 Ejemplo con $mysqli->affected_rows

Estilo orientado a objetos

<?php
mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* Inserción de una fila */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Número de filas afectadas (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* Modificación de una fila */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Número de filas afectadas (UPDATE): %d\n", $mysqli->affected_rows);

/* Eliminación de una fila */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Número de filas afectadas (DELETE): %d\n", $mysqli->affected_rows);

/* Selección de todas las filas */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Número de filas afectadas (SELECT): %d\n", $mysqli->affected_rows);

/* Eliminación de la tabla Language */
$mysqli->query("DROP TABLE Language");
?>

Estilo por procedimientos

<?php
mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* Inserción de una fila */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Número de filas afectadas (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* Modificación de una fila */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Número de filas afectadas (UPDATE): %d\n", mysqli_affected_rows($link));

/* Eliminación de una fila */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Número de filas afectadas (DELETE): %d\n", mysqli_affected_rows($link));

/* Selección de todas las filas */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Número de filas afectadas (SELECT): %d\n", mysqli_affected_rows($link));

/* Eliminación de la tabla "language" */
mysqli_query($link, "DROP TABLE Language");
?>

El resultado de los ejemplos sería:

Número de filas afectadas (INSERT): 984
Número de filas afectadas (UPDATE): 168
Número de filas afectadas (DELETE): 815
Número de filas afectadas (SELECT): 169

Ver también

  • mysqli_num_rows() - Devuelve el número de filas en el conjunto de resultados
  • mysqli_info() - Devuelve información acerca de la última consulta ejecutada

add a note

User Contributed Notes 3 notes

up
47
Anonymous
14 years ago
On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Here's the sum breakdown _per row_:
+0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated
up
10
Jacques Amar
8 years ago
While using prepared statements, even if there is no result set (Like in an UPDATE or DELETE), you still need to store the results before affected_rows returns the actual number:

<?php
$del_stmt
->execute();
$del_stmt->store_result();
$count = $del_stmt->affected_rows;
?>

Otherwise things will just be frustrating ..
up
16
Michael
10 years ago
If you need to know specifically whether the WHERE condition of an UPDATE operation failed to match rows, or that simply no rows required updating you need to instead check mysqli::$info.

As this returns a string that requires parsing, you can use the following to convert the results into an associative array.

Object oriented style:

<?php
preg_match_all
('/(\S[^:]+): (\d+)/', $mysqli->info, $matches);
$info = array_combine ($matches[1], $matches[2]);
?>

Procedural style:

<?php
preg_match_all
('/(\S[^:]+): (\d+)/', mysqli_info ($link), $matches);
$info = array_combine ($matches[1], $matches[2]);
?>

You can then use the array to test for the different conditions

<?php
if ($info ['Rows matched'] == 0) {
echo
"This operation did not match any rows.\n";
} elseif (
$info ['Changed'] == 0) {
echo
"This operation matched rows, but none required updating.\n";
}

if (
$info ['Changed'] < $info ['Rows matched']) {
echo (
$info ['Rows matched'] - $info ['Changed'])." rows matched but were not changed.\n";
}
?>

This approach can be used with any query that mysqli::$info supports (INSERT INTO, LOAD DATA, ALTER TABLE, and UPDATE), for other any queries it returns an empty array.

For any UPDATE operation the array returned will have the following elements:

Array
(
[Rows matched] => 1
[Changed] => 0
[Warnings] => 0
)
To Top