MySQL查询在Phpmyadmin应用时有效,但在通过PHP应用时却不行吗?

时间:2015-09-04 21:41:57

标签: php mysql pdo phpmyadmin

我正在尝试通过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();
}

继承人做什么工作

  • 将创建SQL的触发器复制并粘贴到Phpmyadmin
  • 删除DELIMITERBEGIN END语句 例如如果我将SQL减少到
$migrations[3]['sql']     = "
CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
FOR EACH ROW
        SET NEW.created_at = CURRENT_TIMESTAMP;
";

它确实从PHP运行,问题是我不相信我可以在没有DELIMITERBEGIN END的情况下运行多行语句。
我试过了

  • 转义定界符
  • 使用不同的分隔符

如何让PHP使用DELIMITERBEGIN END语句运行SQL?

1 个答案:

答案 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