Obtaining the Number of Rows Affected by a Query
Problem
You want to know how many rows were changed by a query.
Solution
Some APIs provide the count as the return value of the function that issues the query. Others have a separate function that you call after issuing the query.
Discussion
For queries that affect rows
(UPDATE, DELETE,
INSERT, REPLACE), each API
provides a way to determine the number of rows involved. For MySQL,
“affected by” normally means
“changed by,” so rows that are not
changed by a query are not counted, even if they match the conditions
specified in the query. For example, the following
UPDATE statement would result in an
“affected by” value of zero because
it does not change any columns from their current values, no matter
how many rows the WHERE clause matches:
UPDATE limbs SET arms = 0 WHERE arms = 0;
Perl
In DBI scripts,
the affected-rows count is returned by do( ) or by
execute( ), depending on how you execute the
query:
# execute $query using do( ) my $count = $dbh->do ($query); # report 0 rows if an error occurred printf "%d rows were affected\n", (defined ($count) ? $count : 0); # execute query using prepare( ) plus execute( ) my $sth = $dbh->prepare ($query); my $count = $sth->execute ( ); printf "%d rows were affected\n", (defined ($count) ? $count : 0);
When you use DBI, you have the option of asking MySQL to return the
“matched by” value rather than the
“affected by” value. To do this,
specify mysql_client_found_rows=1 in the options part of the data ...