How to create triggers in Codeigniter's migration library

我怕爱的太早我们不能终老 提交于 2019-12-20 02:42:08

问题


Triggers creation are just not working, I tried everything I can think of, for instance, like that:

$this->db->query("DELIMITER //\r\n
CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts`\r\n
FOR EACH ROW BEGIN\r\n
DELETE FROM page_content WHERE page_content.post_id = OLD.post_id;\r\n
END\r\n
//\r\n
DELIMITER ;");

And whatever I do, I have the feeling it won't create the trigger because Codeigniter create the SQL statement in only one line. Tried with and without the line breaks, still get this message:

Error Number: 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 'DELIMITER // CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts` FOR EAC' at line 1

DELIMITER // CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts` FOR EACH ROW BEGIN DELETE FROM page_content WHERE page_content.post_id = OLD.post_id; END // DELIMITER ;

In PHPMyAdmin, the trigger create works by the way, so the SQL is valid


回答1:


You should remove the delimiter from the trigger while executing via PHP. mysql_ or mysqli_ functions should be able to execute the trigger without the delimiter.

Here is how to do it.

$this->db->query("
CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts`\r\n
FOR EACH ROW BEGIN\r\n
DELETE FROM page_content WHERE page_content.post_id = OLD.post_id;\r\n
END\r\n
//\r\n
");


来源:https://stackoverflow.com/questions/23750476/how-to-create-triggers-in-codeigniters-migration-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!