Saturday, May 18, 2013

How to use mysql_affected_rows?

mysql_affected_rows -- Get number of affected rows in previous MySQL operation

mysql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier. If the link identifier isn't specified, the last link opened by mysql_connect() is assumed.

Example
<?php/* connect to database */$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!
$link) {
    die(
'Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */mysql_query('DELETE FROM mytable WHERE id < 10');printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */mysql_query('DELETE FROM mytable WHERE 0');printf("Records deleted: %d\n", mysql_affected_rows());?>


Output:

Records deleted: 10
Records deleted: 0



Example2
<?php/* connect to database */mysql_connect("localhost", "mysql_user", "mysql_password") 
or
    die("Could not connect: " . mysql_error());mysql_select_db("mydb");
/* Update records 
*/mysql_query("UPDATE mytable SET used=1 WHERE id 
< 10");printf 
("Updated records: 
%d\n", mysql_affected_rows());mysql_query("COMMIT");?> 
Output


Updated Records: 10


No comments:

Post a Comment