mysqli::$affected_rows

mysqli_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli::$affected_rows -- mysqli_affected_rows Liefert die Anzahl der Datensätze, die vom letzten MySQL-Vorgang betroffen waren

Beschreibung

Objektorientierter Stil

Prozeduraler Stil

mysqli_affected_rows(mysqli $mysql): int|string

Gibt die Anzahl der von der letzten INSERT-, UPDATE-,REPLACE- oder DELETE-Abfrage betroffenen Datensätze zurück. Entspricht bei SELECT-Anweisungen mysqli_num_rows().

Parameter-Liste

mysql

Nur bei prozeduralem Aufruf: ein von mysqli_connect() oder mysqli_init() zurückgegebenes mysqli-Objekt.

Rückgabewerte

Eine Ganzzahl größer als Null zeigt die Anzahl der betroffenen oder abgerufenen Datensätze an. Null gibt an, dass bei einer UPDATE-Anweisung keine Datensätze aktualisiert wurden, keine Datensätze mit der WHERE-Klausel übereinstimmen oder dass die Datenbankabfrage noch nicht aufgeführt wurde. -1 gibt an, dass die Datenbankabfrage einen Fehler zurückgegeben hat oder dass mysqli_affected_rows() für eine ungepufferte SELECT-Abfrage aufgerufen wurde.

Hinweis:

Ist die Anzahl der betroffenen Datensätze größer als der maximale Integer-Wert (PHP_INT_MAX), wird die Anzahl der betroffenen Datensätze als Zeichenkette zurückgegeben.

Beispiele

Beispiel #1 $mysqli->affected_rows-Beispiel

Objektorientierter Stil

<?php

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

/* Datensätze einfügen */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Betroffene Datensätze (INSERT): %d\n", $mysqli->affected_rows);

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

/* Datensätze ändern */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Betroffene Datensätze (UPDATE): %d\n", $mysqli->affected_rows);

/* Datensätze löschen */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Betroffene Datensätze (DELETE): %d\n", $mysqli->affected_rows);

/* Alle Datensätze auswählen */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Betroffene Datensätze (SELECT): %d\n", $mysqli->affected_rows);

/* Tabelle Language löschen */
$mysqli->query("DROP TABLE Language");

Prozeduraler Stil

<?php

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

/* Datensätze einfügen */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Betroffene Datensätze (INSERT): %d\n", mysqli_affected_rows($link));

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

/* Datensätze ändern */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Betroffene Datensätze (UPDATE): %d\n", mysqli_affected_rows($link));

/* Datensätze löschen */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Betroffene Datensätze (DELETE): %d\n", mysqli_affected_rows($link));

/* Alle Datensätze auswählen */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Betroffene Datensätze (SELECT): %d\n", mysqli_affected_rows($link));

/* Tabelle Language löschen */
mysqli_query($link, "DROP TABLE Language");

Die obigen Bespiele erzeugen folgende Ausgabe:

Betroffene Datensätze (INSERT): 984
Betroffene Datensätze (UPDATE): 168
Betroffene Datensätze (DELETE): 815
Betroffene Datensätze (SELECT): 169

Siehe auch

  • mysqli_num_rows() - Ermittelt die Anzahl der Zeilen einer Ergebnismenge
  • mysqli_info() - Ruft Informationen über die zuletzt ausgeführte Abfrage ab

add a note add a note

User Contributed Notes 7 notes

up
45
Anonymous
13 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
7 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
)
up
-1
lucgommans.nl
1 year ago
Under the hood, this calls into mysql_affected_rows (1). The MariaDB function ROW_COUNT() mentions (2) that it is the equivalent of that C API function. These two lines, SQL followed by PHP, should be equivalent:

SELECT ROW_COUNT();
$db->affected_rows;

I found this useful to double check things in an SQL prompt, to make sure affected_rows is reflecting what I expect (changed rows as opposed to matched rows in an update statement), which indeed it did.

1. https://github.com/php/php-src/blob/1521cafee29e23ca147ec777f3770a7ac46c6880/ext/mysqli/mysqli_api.c#L36-L49
2. https://mariadb.com/kb/en/row_count/
up
-7
fastest963 at gmail dot com
10 years ago
empty($db->affected_rows) will return TRUE even if affected_rows is greater than 0. Manually check < 1 if you're looking for failure.
up
-11
anonymous
8 years ago
This may seem obvious, but if you do an UPDATE with each of the values in your SET clause having the exact same value that is already in the table, then affected_rows returns 0.  For example:

<?php
    $mysqli
= new mysqli($host, $usr, $pwd, $db, $port);
   
$appointment_date = "2015-12-07";
   
$sql = "update appointments set appointment_date = ? where appointment_id = 78";
   
$stmt = $mysqli->prepare($sql);
   
$stmt->bind_param("s",$appointment_date);
   
$stmt->execute();
    echo
$mysqli ->affected_rows . "<br>";
?>

This returns 1 the first time I run it after changing the value of the $appointment_date variable.  When I run it a second time (making no changes), it returns 0.  I also verified the same behavior without using prepared statements.
up
-16
oilpc at oilpc dot com
15 years ago
For "INSERT" or "UPDATE" statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
<?php
if ($mysqli->affected_rows==1){
    echo
"success";
}
else {
    echo
"fail";
}
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of "INSERT IGNORE" statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
<?php
if ($mysqli->affected_rows!=-1){
    echo
"success";// for "INSERT IGNORE" statements will not occur if there were any duplicate key errors ignored during execution of the query
}
else {
    echo
"fail";// "INSERT IGNORE" statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
}

// Example below works for "INSERT IGNORE" stattements, too
if ($mysqli->sqlstate=="00000"){
    echo
"success";
}
else {
    echo
"fail";
}
?>
To Top