Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL trigger if condition exists

Tags:

mysql

triggers

I'm trying to write an update trigger that will only update a password when a new password is set in the update statement but I'm having a terrible time trying to nail down the syntax. This should be a no-brainer but I'm just not finding the solution.

Here's my code:

CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
  IF (NEW.password <> '') THEN
        SET NEW.password = PASSWORD(NEW.password);
  END IF;
END;

I've tried:

IF (NEW.password <> NULL) THEN

IF (NEW.password) THEN

IF NEW.password <> NULL THEN

IF (NEW.password > 0) THEN

IF (NEW.password != NULL) THEN

And I'm sure many other combinations but it's just not working. Does anyone have any insight?

like image 674
gurun8 Avatar asked Mar 21 '11 01:03

gurun8


1 Answers

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead
DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;
like image 200
RichardTheKiwi Avatar answered Sep 28 '22 03:09

RichardTheKiwi