Mysql_affected_rows
(PHP 3, PHP 4)
Mysql_affected_rows -- gets the number of records affected by the previous MySQL operation
Description
Int mysql_affected_rows ([Resource link_identifier])
Mysql_affected_rows () returns the number of rows affected by the last insert, update, or delete query associated with the connection handle. If the connection handle is not specified, the last connection handle opened by the mysql_connect () function is used by default.
Note: If you use transactions, you need to call the mysql_affected_rows () function after insert, update, or delete queries, instead of after the commit command.
If the last operation is a delete query without any conditions (where), all records in the table will be deleted, but the return value of this function is 0.
Note: When an update query is used, MySQL does not update columns with the same Original Value and new value. In this way, the return value of the mysql_affected_rows () function is not necessarily the number of records that meet the query conditions. Only the number of modified records is returned.
The mysql_affected_rows () function is not applicable to select statements. It is only applicable to statements that can modify records. Use the mysql_num_rows () function to obtain the number of records returned by the SELECT statement.
If the last query fails, the function returns-1. Example 1. delete operation
<? PHP
/* Connect to the database */
Mysql_pconnect ("localhost", "mysql_user", "mysql_password") or
Die ("cocould not connect". mysql_error ());
Mysql_select_db ("mydb ");
/* This will return a valid number of deleted records. */
Mysql_query ("delete from mytable where ID <10 ");
Printf ("records deleted: % d \ n", mysql_affected_rows ());
/* The delete statement without any condition (where) returns 0 */
Mysql_query ("delete from mytable ");
Printf ("records deleted: % d \ n", mysql_affected_rows ());
?>
The preceding example shows the following running result:
Records deleted: 10
Records deleted: 0
Example 2. Update operation
<? PHP
/* Connect to the database */
Mysql_pconnect ("localhost", "mysql_user", "mysql_password") or
Die ("cocould not connect". mysql_error ());
Mysql_select_db ("mydb ");
/* Update record */
Mysql_query ("Update mytable set used = 1 where ID <10 ");
Printf ("updated records: % d \ n", mysql_affected_rows ());
Mysql_query ("commit ");
?>
The preceding example shows the following running result:
Updated records: 10
See mysql_num_rows () and mysql_info ().