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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件