我正在尝试通过PHP将触发器应用于现有的表和列。 执行PHP代码时,不会抛出任何错误,但不会创建触发器。
我的PHP代码是:
//file: migrations.php
// created_at column already defined in a previous migration
//...
$migrations[3]['message'] = "added created_at, updated_at columns on rate table";
$migrations[3]['created'] = "2015-09-05 08:28:00";
$migrations[3]['sql'] = "
DELIMITER |
CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
FOR EACH ROW
BEGIN
SET NEW.created_at = CURRENT_TIMESTAMP;
END |
DELIMITER ;
";
// apply migration
foreach ($migrations as $key => $value) {
// run the migration SQL for the current iteration
$sth = $dbh->prepare( $value['sql'] );
$sth->execute();
}
继承人做什么工作
DELIMITER
和BEGIN
END
语句
例如如果我将SQL减少到$migrations[3]['sql'] = "
CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
FOR EACH ROW
SET NEW.created_at = CURRENT_TIMESTAMP;
";
它确实从PHP运行,问题是我不相信我可以在没有DELIMITER
和BEGIN
END
的情况下运行多行语句。
我试过了
如何让PHP使用DELIMITER
和BEGIN
END
语句运行SQL?
答案 0 :(得分:2)
是的,你必须摆脱那些DELIMITER
,只需要下面的代码
$migrations[3]['sql'] = "
CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
FOR EACH ROW
BEGIN
SET NEW.created_at = CURRENT_TIMESTAMP;
END;";
请看另一篇帖子说同样的事情PHP: multiple SQL queries in one mysql_query statement