duancan65665 2015-09-04 21:41
浏览 48
已采纳

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

I am trying to apply a trigger to an existing table and column through PHP. When executing the PHP code, no error is thrown, but the trigger is not created.

My PHP code is:

//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();
}

heres what does work

  • Copying and pasting the trigger creating SQL into Phpmyadmin
  • getting rid of the DELIMITER and BEGIN END statements e.g. if I reduce the SQL to
$migrations[3]['sql']     = "
CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
FOR EACH ROW
        SET NEW.created_at = CURRENT_TIMESTAMP;
";

It does run from PHP, problem is I dont believe I can run multiline statements without DELIMITER and BEGIN END.
I have tried

  • escaping the delimiter character
  • using different delimiter characters

What can I do to get the PHP to run the SQL with the DELIMITER and BEGIN END statements?

  • 写回答

1条回答 默认 最新

  • dtwye28880 2015-09-04 21:51
    关注

    yes, you will have to get rid of those DELIMITER, just have the below code

    $migrations[3]['sql'] = "
    CREATE TRIGGER rate_created_at BEFORE INSERT ON rate
    FOR EACH ROW
        BEGIN
            SET NEW.created_at = CURRENT_TIMESTAMP;
        END;";
    

    See this another post saying same thing PHP: multiple SQL queries in one mysql_query statement

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?