0

I had an issue when I tried to add mysql trigger query via codeigniter $this->db->query(); but it shows syntax error. Here is code below:

  $this->db->query("DELIMITER $$ 
        CREATE TRIGGER `after_stuload_insert_info_data` AFTER INSERT 
        ON `{$this->tables->hesa_stuload_student_info}`
         FOR EACH ROW BEGIN 
          INSERT INTO `{$this->tables->hesa_student_reportperiod}` (hesa_course_relation_instance_id, student_data_id)
           VALUES (new.hesa_course_relation_instance_id, new.student_data_id); 
         END$$  
         DELIMITER ; ");

Can you Please tell what is the wrong with this code. Thanks in advance. Check below for the error.

enter image description here

2 Answers2

1

DELIMITER is a directive for clients that have a parser looking for semicolons. Using a script, you don't use this at all. Nor do you put the $$ at the end.

Just this:

$this->db->query("CREATE TRIGGER
... the rest of the trigger ...
END");

Also, if you're using a variable for the table name (Red flag! Why are you creating triggers from web code?) you should probably also dynamically generate the trigger name. Trigger names have to be unique within a schema.

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427
0

You usually cannot execute multiple queries in a single request. Most likely you need to do something like this:

  $this->db->query("DELIMITER $$"); 
  $this->db->query("CREATE TRIGGER `after_stuload_insert_info_data` AFTER INSERT 
        ON `{$this->tables->hesa_stuload_student_info}`
         FOR EACH ROW BEGIN 
          INSERT INTO `{$this->tables->hesa_student_reportperiod}` (hesa_course_relation_instance_id, student_data_id)
           VALUES (new.hesa_course_relation_instance_id, new.student_data_id); 
         END$$"); 
  $this->db->query("DELIMITER ; ");

According to another answer here you don't even need the delimiter statements, when creating triggers in this kind of environment, at all.

Community
  • 1
  • 1
Uueerdo
  • 15,723
  • 1
  • 16
  • 21