> -----Original Message----- > From: Jonathan Mangin [mailto:[EMAIL PROTECTED] > Sent: Tuesday, April 04, 2006 3:14 PM > To: Garrett, Philip (MAN-Corporate); dbi-users@perl.org > Subject: Re: Not exactly a dbi question > > > The execute() method returns the number of rows affected for DML > (insert/update/delete) statements, e.g. > > my $rows = $sth->execute($sql) || die "can't update: " . > $sth->errstr; > print "Updated $rows rows.\n"; > > The "|| die" stuff still works even when 0 rows are affected because in that case, it returns "0 but true". > > Philip > > > Thanks, Philip, that works though not as expected. > Running the following snippet multiple times: > > my $user_id = 'harvey'; > my $user_type = 'PAT'; > my $last_name = 'Wallbanger'; > my $state_id = '1'; > my $org_id = 'IN2'; > my $email = '[EMAIL PROTECTED]'; > > my $sql = "update user > set type = ?, > last_name = ?, > state_id = ?, > org_id = ?, > email = ? > where id = ?"; > my $sth = $dbh->prepare($sql); > my $result = $sth->execute($user_type, $last_name, $state_id, > $org_id, $email, $user_id) || die > "Cannot update: " . $sth->errstr(); my $action = defined($result) ? 'MOD' : undef; > > print "$result\n"; > print "$action\n"; > > always returns '1' and 'MOD' whether an update actually occurred or > not. How can I define $action only upon an actual update? Perhaps I > need to upgrade?
No upgrade necessary. The $result will *always* be defined unless there was an error. Otherwise, it contains a numeric value for the number of rows affected (which also happens to always evaluate to true in boolean context). Try this: my $rows = $sth->execute(...) || die $sth->errstr; if ($rows == 0) { print "No rows updated.\n"; } else { printf "Updated $rows rows.\n"; } Philip