如何在Codeigniter的迁移库中创建触发器

时间:2014-05-20 03:18:29

标签: php mysql codeigniter codeigniter-2

触发器创建无法正常工作,我尝试了所有我能想到的,例如:

$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 ;");

无论我做什么,我都觉得它不会创建触发器,因为Codeigniter只在一行中创建了SQL语句。尝试使用和不使用换行符,仍然会收到此消息:

错误号码: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 ;

在PHPMyAdmin中,触发器创建顺便进行,因此SQL有效

1 个答案:

答案 0 :(得分:6)

您应该在通过PHP执行时从触发器中删除分隔符。     mysql_或mysqli_函数应该能够在没有的情况下执行触发器     分隔符。

以下是如何做到的。

$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
");