Search code examples
mysqlsqltriggersuser-registration

How to create a trigger to insert new users details to another table?


Im trying to "synchronize" an external forum script (SMF) with my website. Thats means, when a user registers in my website, a trigger insert the user details (username, password and email) in the external forum members table. Something like that, but its wrong, sql error.

CREATE TRIGGER forumReg 
AFTER INSERT ON hotaru_users 
FOR EACH ROW
BEGIN
    INSERT INTO forum_members (member_name, email_address, passwd)
    VALUES (NEW.user_username, NEW.user_email, NEW.user_password);
END

hotaru_users is my website users table, forum_members is the external forum users table, both tables are in the same mysql database

the error

Erro

consulta SQL:

CREATE TRIGGER forumReg AFTER INSERT ON hotaru_users
FOR EACH
ROW
BEGIN
INSERT INTO forum_members( member_name, email_address, passwd )
VALUES (
NEW.user_username, NEW.user_email, NEW.user_password
);

Mensagens do MySQL : Documentação
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 6 

Solution

  • Either remove the BEGIN, END:

    CREATE TRIGGER forumReg 
    AFTER INSERT ON hotaru_users 
    FOR EACH ROW
        INSERT INTO forum_members (member_name, email_address, passwd)
        VALUES (NEW.user_username, NEW.user_email, NEW.user_password);
    

    or change the delimiter for the creation of the trigger:

    DELIMITER $$
    CREATE TRIGGER forumReg 
    AFTER INSERT ON hotaru_users 
    FOR EACH ROW
    BEGIN
        INSERT INTO forum_members (member_name, email_address, passwd)
        VALUES (NEW.user_username, NEW.user_email, NEW.user_password);
    END 
    $$
    DELIMITER ;