Function to revert mysql statement

873 Views Asked by At

How can I implement a undo changes function in my php application, so if the user for example added a new member to a group, or deleted item a notification message will appear: The selected item have been deleted, undo delete action(link that trigger the undo function).

The following is a working code:

public function deleteRecord($id) {
            $group = $this->query('SET autocommit=0');
            $group = $this->query('DELETE FROM  `members` WHERE memberID = '.$id.'');

    }


    public function undo_delete() {
            $member = $this->query('rollback');
    if($member) {
            trigger_error('Undo action has been completed. ', E_USER_NOTICE);
            return true;
}

    }

The only problem with this code is the transaction has not been submitted, so rollback or log out will undo all the changes that has been done during the user session, I am not sure if this is the best approach to create a redo function, any suggestions?

2

There are 2 best solutions below

4
On

You will not be able to undo with 2 different requests .Because when you will call the undo . It will undo all delete happened for all the members . To solve it I would suggest -

  1. You create a new table where you keep the information of the deleted record, eg- deleted_members.
  2. When user calls for undo fetch the data from the deleted_members table and insert into original members table.
  3. After successful insert in original table ,remove the data from the delete information table.

I hope this helped.

1
On

Transactions do not survive across PHP requests. If a transaction is still open at the end of the first request, it will be implicitly rolled back when the MySQL connection closes at the end of the request. As a result, there is no longer a transaction to roll back when an undo is requested later.

If you want to implement this functionality, it will need to be implemented in application logic.