tags:

views:

47

answers:

3

I am trying to create a MySQL Trigger to disable someone's account if they have logged in to the site 3 times. I have tried to create this trigger using the following code, but it is not setting is_active to 0 no matter what times_logged_in is. Any help would be appreciated.

CREATE TRIGGER updateTrigger AFTER UPDATE ON users
FOR EACH ROW
BEGIN
UPDATE users SET is_active=0 WHERE NEW.is_code=1 
AND NEW.times_logged_in>=3
AND NEW.user_id=user_id;
END;
A: 

I'm not sure where user_id comes from in your trigger, looks like an extraneous check, try this:

CREATE TRIGGER updateTrigger AFTER UPDATE ON users
FOR EACH ROW
BEGIN
  UPDATE users SET is_active=0 WHERE NEW.is_code=1 
  AND NEW.times_logged_in>=3
END;

Also, be sure that is_code = 1 is actually matching on the users you're updating, if it's not, it won't update any rows.

Nick Craver
I have tried your code, but it is still not working. I have also double checked that is_code = 1 is matching, but the trigger still does not seem to be doing anything.
Mike D
@Mike D - The `is_code = 1` is matching the **update statment**, or the existing row?, same for the `times_logged_in`?
Nick Craver
The is_code = 1 is matching the existing row. The times_logged_in is matching the update statement, it is being incremented by 1.
Mike D
@Mike - Is is_code matching the updated row? Not sure what is_code is referring to. Posting the update statement may help here as well.
Nick Craver
is_code=1 means that the user should be logging in with an access code instead of a user name or password.The update statement is as follows: UPDATE users SET times_logged_in=times_logged_in+1 WHERE user_id=10
Mike D
A: 

I would use a BEFORE UPDATE trigger instead:

CREATE TRIGGER updateTrigger BEFORE UPDATE ON users 
FOR EACH ROW 
BEGIN
IF NEW.is_code=1 AND NEW.times_logged_in>=3 THEN
   SET NEW.is_active=0;
END IF;
END;
BenV
A: 

You've hit a limitation of MySQL. Your table users invokes the trigger (AFTER UPDATE ON users), therefore the triggered code cannot modify it. See the MySQL-Manual:

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

titanoboa