mysqli_affected_rows
(PHP 5 CVS only)
mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation
Description
mixed
mysqli_affected_rows ( object link)
mysqli_affected_rows() returns the number of rows affected by the last
INSERT, UPDATE, or DELETE query associated with the provided link
parameter. If the last query was invalid, this function will return -1.
Note:
When deleting the entire contents of a table (i.e. 'DELETE FROM foo'), this function will
not return the number of rows that were actually deleted.
The mysqli_affected_rows() function only works with queries which modify
a table. In order to return the number of rows from a SELECT query, use the
mysqli_num_rows() function instead.
Example 1. Delete-Query Procedural style:
<?php /* connect to database */ $link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mydb") or die("Could not connect: " . mysqli_connect_error()); /* this should return the correct numbers of deleted records */ mysqli_query($link, "DELETE FROM mytable WHERE id < 10"); printf("Records deleted: %2d\n", mysqli_affected_rows($link));
/* without a where clause in a delete statement, it should return 0 */ mysqli_query($link, "DELETE FROM mytable"); printf("Records deleted: %2d\n", mysqli_affected_rows($link));
/* close connection */ mysqli_close($link); ?>
|
Object oriented style:
<?php /* connect to database */ $mysql = mysqli_connect("localhost", "mysql_user", "mysql_password", "mydb") or die("Could not connect: " . mysqli_connect_error()); /* this should return the correct numbers of deleted records */ $mysql->query("DELETE FROM mytable WHERE id < 10"); printf ("Records deleted: %2d\n", $mysql->affected_rows());
/* without a where clause in a delete statement, it should return 0 */ $mysql->query("DELETE FROM mytable"); printf ("Records deleted: %2d\n", $mysql->affected_rows());
/* close connection */ $mysql->close(); ?>
|
The above examples would produce the following output:
Records deleted: 10
Records deleted: 0 |
|
Example 2. Update-Query Procedural style:
<?php /* connect to database */ $link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mydb") or die("Could not connect: " . mysqli_connect_error()); /* Update records */ mysqli_query($link, "UPDATE mytable SET used=1 WHERE id < 10"); printf ("Updated records: %d\n", mysqli_affected_rows($link));
/* close connection */ mysqli_close($link); ?>
|
Object oriented style:
<?php /* connect to database */ $mysql = mysqli_connect("localhost", "mysql_user", "mysql_password", "mydb") or die("Could not connect: " . mysqli_connect_error()); /* Update records */ $mysql->query("UPDATE mytable SET used=1 WHERE id < 10"); printf ("Updated records: %d\n", $mysql->affected_rows($link));
/* close connection */ $mysql->close($link); ?>
|
The above examples would produce the following output:
|
See also: mysqli_num_rows(),
mysqli_info().