How to know the number of rows deleted in mysql?

11,493

Solution 1

How to know the no of deleted rows in codeigniter provided that $this->db->affected_rows() returns every time ie. on success or on fail also

I don't use CodeIgniter, but normally, affected_rows( ) should return the number of rows affected. That means, if the query succeeded, it should always be an integer. If 0 is returned, no rows are deleted, if > 0, that number is deleted.

Solution 2

$this->db->where($conditions)->delete('mytable');
return $this->db->affected_rows(); 

Solution 3

Have you tested it out, according to codeigniters website there is a hack that returns correct amount of rows, that's turned on by default.

http://codeigniter.com/user_guide/database/helpers.html

Solution 4

According to the Codeigniter userguide it returns the correct number of rows:

"Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file."

so therefore this should work:

 $this->db->delete('1', 'your_table');
 echo ($this->db->affected_rows()." rows were deleted");

If it doesn't work, then just do this as a non-ideal workaround

$count = $this->db->count_all('your_table');
$this->db->delete('1', 'your_table');
$new_count = $this->db->count_all('your_table');
if ($new_count > $count)
{
    echo (($new_count-$count)." rows was deleted");
}
else
{
    echo "nothing deleted";
}
Share:
11,493
mohan.gade
Author by

mohan.gade

Profession : Software Engineer

Updated on June 04, 2022

Comments

  • mohan.gade
    mohan.gade almost 2 years

    How to know the no of deleted rows in codeigniter provided that $this->db->affected_rows() returns every time ie. on success or on fail also