通过PHP创建mysql触发器?

时间:2010-09-21 17:34:08

标签: php mysql triggers mysqli

我在PHP5.3中执行以下内容:

$sql = "
CREATE TRIGGER `_photo_fulltext_insert` AFTER INSERT ON `photo` FOR EACH ROW INSERT INTO `_photo_fulltext` SELECT * FROM `photo` WHERE `id`=NEW.`id`;
CREATE TRIGGER `_photo_fulltext_delete` AFTER DELETE ON `photo` FOR EACH ROW DELETE FROM `_photo_fulltext` WHERE `id`=OLD.`id`;

DELIMITER |
CREATE TRIGGER `_photo_fulltext_update` AFTER UPDATE ON `photo`
  FOR EACH ROW BEGIN
    DELETE FROM `_photo_fulltext` WHERE `id`=NEW.`id`;
    INSERT INTO `_photo_fulltext` SELECT * FROM `photo` WHERE `id`=NEW.`id`;
  END;
|
DELIMITER ;
";

$mysqli->multi_query($sql);

未创建“photo_fulltext_update”触发器。此语句在phpMyAdmin中运行(并创建所有触发器)。我在网上看过MySQL服务器根本不支持DELIMITER语句,所以我正在寻找一种方法来重写这个多步CREATE TRIGGER语句,以便mysqli :: multi_query可以将它发送到MySQL 。

谢谢!

3 个答案:

答案 0 :(得分:12)

虽然mysqliDELIMITER语句中的multi-query没有任何内容,但在普通查询中它实际上对任何分隔符都没有做任何事情,所以只需推动你的触发​​器一个接一个地说:

$ cat i.php 
<?php
$mysqli = new mysqli('localhost', 'test', '', 'test');
$sql = "
CREATE TRIGGER `_foo_fulltext_update` AFTER UPDATE ON `foo`
  FOR EACH ROW BEGIN
    DELETE FROM `bar` WHERE `bar`=NEW.`bar`;
    INSERT INTO `bar` (bar) SELECT bar FROM `foo` WHERE `bar`=NEW.`bar`;
  END;
";
$mysqli->query($sql);
var_dump($mysqli->error);
$ php i.php 
string(0) ""
$ mysql
mysql> use test;

Database changed
mysql> show triggers\G
*************************** 1. row ***************************
             Trigger: _foo_fulltext_update
               Event: UPDATE
               Table: foo
           Statement: BEGIN
    DELETE FROM `bar` WHERE `bar`=NEW.`bar`;
    INSERT INTO `bar` (bar) SELECT bar FROM `foo` WHERE `bar`=NEW.`bar`;
  END
              Timing: AFTER
             Created: NULL
            sql_mode: 
             Definer: root@localhost
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

答案 1 :(得分:1)

这可能会对您有所帮助:

PHP: multiple SQL queries in one mysql_query statement

答案 2 :(得分:0)

这也可能有所帮助: 以下内容在选择表上创建触发器。更改代码,它可能会做你想要的。 https://github.com/junicom/mysqltriggerscript