11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 33 • MYSQL TRIGGERSFOR EACH ROWAs you can see, it’s possible to specify whether the trigger should execute before or after the query;whether it should take place on row insertion, modification, or deletion; and to what table the triggerapplies.The DEFINER clause determines which user account will be consulted to determine whetherappropriate privileges are available to execute the queries defined within the trigger. If defined, you’llneed to specify both the username and hostname using 'user@host' syntax (for example,'jason@localhost'). If CURRENT_USER is used (the default), then the privileges of whichever account hascaused the trigger to execute will be consulted. Only users having the SUPER privilege are able to assignDEFINER to another user.■ Tip If you‘re using a version of <strong>MySQL</strong> earlier than 5.1.6, you need the SUPER privilege to create triggers;starting with 5.1.6, you can do so if your account is assigned the TRIGGER privilege.The following example implements the helpdesk trigger described earlier in this chapter:DELIMITER //CREATE TRIGGER au_reassign_ticketAFTER UPDATE ON techniciansFOR EACH ROWBEGINIF NEW.available = 0 THENUPDATE tickets SET technician_id=0 WHERE technician_id=NEW.id;END IF;END;//■ Note You may be wondering about the au prefix in the trigger title. See the sidebar “Trigger NamingConventions” for more information about this and similar prefixes.For each row affected by an update to the technicians table, the trigger will update the ticketstable, setting tickets.technician_id to 0 wherever the technician_id value specified in the UPDATEquery exists. You know the query value is being used because the alias NEW prefixes the column name. It’salso possible to use a column’s original value by prefixing it with the OLD alias.Once the trigger has been created, go ahead and test it by inserting a few rows into the tickets tableand executing an UPDATE query that sets a technician’s availability column to 0:UPDATE technicians SET available=0 WHERE id=1;Now check the tickets table, and you’ll see that both tickets that were assigned to Jason areassigned no longer.653

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!