Skip to content
PHP Logo

How can triggers be used in PHP to handle specific conditions for updating tables and inserting data into other tables?

Triggers in PHP can be used to handle specific conditions for updating tables and inserting data into other tables by defining actions that automatically occur when a specified event takes place in the database. This can help maintain data integrity and enforce business rules without the need for manual intervention.

php
// Create a trigger in PHP to update a table when specific conditions are met
$query = "CREATE TRIGGER update_table_trigger 
            AFTER UPDATE ON original_table 
            FOR EACH ROW 
            BEGIN 
                IF NEW.column_name = 'specific_value' THEN 
                    UPDATE other_table 
                    SET column_to_update = NEW.new_value 
                    WHERE id = NEW.id; 
                END IF; 
            END;";
            
// Execute the trigger creation query
mysqli_query($connection, $query);