0

I am using Mysql and trying to create a trigger on a table that prevents a specific record from being deleted or updated, example I have a table demo

id    username    password
1     dames       t312llok
2     sauce       12ff1fff1
3     hynes       5656166oo9

I would like to prevent the record:

id    username    password
1     dames       t312llok

from being deleted or updated via the use of a trigger

dames
  • 1,421
  • 8
  • 35
  • 55

1 Answers1

0

If you are using MySQL 5.5 or higher, this is simple.

DELIMITER $$
DROP TRIGGER IF EXISTS demo_bd $$
CREATE TRIGGER demo_bd BEFORE DELETE ON demo FOR EACH ROW
BEGIN
  IF OLD.id = 1 THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This magical user cannot be deleted';
  END IF;
END $$
DELIMITER ;

For the update, it's exactly the same code, with minor tweaks.

DELIMITER $$
DROP TRIGGER IF EXISTS demo_bu $$
CREATE TRIGGER demo_bu BEFORE UPDATE ON demo FOR EACH ROW
BEGIN
  IF OLD.id = 1 THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This magical user cannot be updated';
  END IF;
END $$
DELIMITER ;

Also... don't store passwords in the database.

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427