I need Primary keys of the affected rows to be returned after updating a MYSQL table using my PHP Code. Is there anyway to achieve this?
You will need to fetch the primary keys before performing the UPDATE
:
SELECT primary_key_columns FROM my_table WHERE status = 'O';
UPDATE my_table SET status = 'E' WHERE status = 'O';
However, if you have concurrent connections that might alter my_table
between the two statements, it's possible that the results of the keys returned by the first SELECT
statement will not fully match the records updated by the second UPDATE
statement.
To prevent this, you would need to perform the operations in a transaction (but note that transactions require support from your storage engine - InnoDB is usually used for this purpose):
START TRANSACTION;
SELECT primary_key_columns FROM my_table WHERE status = 'O' FOR UPDATE;
UPDATE my_table SET status = 'E' WHERE status = 'O';
COMMIT;
One way of doing what you want is previously SELECT the primary keys with the conditions for the update BEFORE you do the update.
If your query is
Update * from "table" where Y
you would have to do the following:
Select "Primary key" from "table" where Y
Update X from "table" where Y
Hope this helps!