简体   繁体   English

选择最后受影响的行

[英]Select the last affected rows

I have updated my records based on specific condition after that I want to know the ids from the affected rows. 我已经根据特定条件更新了记录,之后我想知道受影响的行中的ID。

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

Now after executing this query I want to know the affected rows. 现在执行此查询后,我想知道受影响的行。

Simple yet effective 简单而有效

$last_id = mysqli_insert_id($conn);

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

You must first fetch the IDs, and then perform the update. 您必须首先获取 ID, 然后执行更新。 If concurrency is a concern, you can use a locking read (provided that your table is stored in a transactional engine, such as InnoDB): 如果需要考虑并发性,则可以使用锁定读取 (前提是您的表存储在事务引擎中,例如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);

The only way I can think of is to first sleect rows that would be updated with the update statement, those are: 我能想到的唯一方法是首先选择将使用update语句更新的行,这些行是:

$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. 我们添加xxx !='".$x."'因为如果xxx值已经是$x那么这些行将不会受到影响。

Next you run the update 接下来,您运行更新

$sql = mysqli_query("update table set xxx='".$x."' where yyy='".$y."'");
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. 如果只想更新真正更改的行,请通过LAST_INSERT_ID添加有条件的user_id更新,并检查行中的数据是否要更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM