Preventing MySQL INSERTS with a Trigger
To prevent inserting a row when a specific condition is met, such as a birthdate set in the future, you can create a trigger. Here's how:
CREATE TRIGGER foo BEFORE INSERT ON table FOR EACH ROW BEGIN IF NEW.birthdate > CURRENT_DATE() THEN SIGNAL SQLSTATE '45000'; END IF; END;
Canceling the Insert
To cancel the insert within the trigger, use the SIGNAL SQLSTATE syntax. For example, to raise an error when the birthdate is in the future, you would use:
SIGNAL SQLSTATE '45000';
This will throw an unhandled user-defined exception and prevent the insertion.
The above is the detailed content of How Can I Prevent MySQL Inserts Based on a Condition Using Triggers?. For more information, please follow other related articles on the PHP Chinese website!