Home » Php » php – Select the last affected rows

php – Select the last affected rows

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have updated my records based on specific condition after that I want to know the ids from the affected rows.

$sql = mysqli_query("update table set xxx='".$x."' where yyy='".$y."'");

Now after executing this query I want to know the affected rows.

How to&Answers:

Simple yet effective

$last_id = mysqli_insert_id($conn);

http://www.w3schools.com/php/php_mysql_insert_lastid.asp

Answer:

You must first fetch the IDs, and then perform the update. If concurrency is a concern, you can use a locking read (provided that your table is stored in a transactional engine, such as InnoDB):

$mysqli->autocommit(FALSE);

$select = $mysqli->prepare('SELECT id FROM table WHERE yyy = ? FOR UPDATE');
$select->bind_param('s', $y);
$select->execute();

$update = $mysqli->prepare('UPDATE table SET xxx = ? WHERE yyy = ?');
$update->bind_param('ss', $x, $y);
$update->execute();

$mysqli->commit();

// here are the IDs that were updated
$select->bind_result($id);
while ($select->fetch()) printf('Updated id: %s\n', $id);

Answer:

The only way I can think of is to first sleect rows that would be updated with the update statement, those are:

$updatableIds = mysqli_query("SELECT id FROM table WHERE xxx !='".$x."' AND yyy='".$y."'");

we add xxx !='".$x."' because if value of xxx already was $x those rows would not be affected.

Next you run the update

$sql = mysqli_query("update table set xxx='".$x."' where yyy='".$y."'");

Answer:

UPDATE users
SET type = '3'
WHERE type = '2';

To find out the last affected row right after the statement, it should be slightly updated as follows:

UPDATE users
SET type = '3',
    user_id=LAST_INSERT_ID(user_id)
WHERE type = '2';

// use function

 function updateAndGetId($value)
   {
       $query ="UPDATE users
    SET type = '$value',
        user_id=LAST_INSERT_ID(user_id)
    WHERE type = '2'";
      mysql_query($query)
    return mysql_insert_id();
   }
   $lastUpdatedRow = updateAndGetId(3);

In case you want to update only really changed row, add a conditional update of the user_id through the LAST_INSERT_ID and check if the data is going to change in the row.