Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get affected rows after update statement in mysql?

Tags:

php

mysql

How to get affected rows (not just the number of rows affected) after update statement in mysql.

like image 669
Amit Jha Avatar asked May 15 '12 07:05

Amit Jha


People also ask

How can you know the number of rows affected by last SQL statement?

@@ROWCOUNT – Get the Number of Rows Affected by the Last Statement in SQL Server. In SQL Server, you can use the @@ROWCOUNT system function to return the number of rows affected by the last T-SQL statement. For example, if a query returns 4 rows, @@ROWCOUNT will return 4.

How do you get the number of rows affected by a query?

MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.

What is Row_count () in MySQL?

In MySQL the ROW_COUNT() function is used to return the number of rows affected by the previous SQL statement. If the previous statement was not one that could potentially change data rows or you can say, it wasn't an INSERT, UPDATE, DELETE or other such statement this function will return -1.

What do Mysql_affected_rows () function do?

The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.


3 Answers

mysql_info — Get information about the most recent query

$recent = mysql_info();

Useful implementation Example

like image 77
Gustav Avatar answered Sep 28 '22 00:09

Gustav


If you want the actual rows and not the amount of affected rows, simply fetch them before doing the update.

Afterwards you can compare update values with selected values and filter them by difference.

Example with CodeIgniter:

$arr_where = array('date >=' => date('Y-m-d H:i:s'));

$query = $this->db->get_where('table', $arr_where);

$arr_update = array('status' => 'TRUE');

if ($this->db->update('table', $arr_update, $arr_where)) {

    foreach($query->result() as $row)
        foreach(array_keys($arr_update) as $h)
            if ($row->$h != $arr_update[$h])
                echo "This row ({$row->id}) had it's {$h} changed!<br />";

}

Sorry for supplying solution in CodeIgniter, but I found it to be the simpliest example.

To see what the $this->db functions do, see Active Records.

like image 38
Robin Castlin Avatar answered Sep 27 '22 23:09

Robin Castlin


You could try using:

SET @uids := '';
UPDATE <table>
 SET <column1> = <value>
 WHERE <column2> = <value> 
   AND ( SELECT @uids := CONCAT_WS(',', @uids, id) );
SELECT TRIM(LEADING ',' FROM @uids);
like image 21
Slipstream Avatar answered Sep 28 '22 00:09

Slipstream