doufei6456 2018-05-12 09:54
浏览 65
已采纳

MySQL Trigger无法在PHP中运行

TL;DR: Query works from MySQL CLI but NOT from PHP, as if the triggers were not fired by PHP.

I have a mySQL structure which looks like this:

  • entity is the "parent" table with id as PK
  • contact is a "child" table with entity_id as PK and FK on entity
  • person is a "grand-child" table with entity_id as PK and FK on contact

I have created some triggers so that when I insert a new row in contact, it first inserts a new row in entity and uses the new id as entity_id. Idem for person and contact. Triggers are all made on the same model, here's one:

DELIMITER #
DROP TRIGGER IF EXISTS contact_insert_trig;
CREATE TRIGGER contact_insert_trig BEFORE INSERT ON `contact`
FOR EACH ROW BEGIN
    INSERT INTO entity (cat_id) values (1);
    SET NEW.entity_id = (SELECT id FROM entity ORDER BY id DESC LIMIT 1);
    SET NEW.entity_cat_id = 1;
END; #

So, for instance, when I insert a new row in person, the first trigger creates a row in contact which, via the second trigger, creates a row in entity, all with matching ids.

This WORKS in MySQL but NOT in PHP. The same query:

INSERT INTO person (first_name, last_name) VALUES ("Bob", "McIntosh")

works in the mySQL CLI (all rows are created and match up) but fails when called with mysqli->query() in PHP7 with the error:

Field 'entity_id' doesn't have a default value

How can I make it work in PHP as well? Or do I have to go through the process of creating all parent tables manually?

  • 写回答

1条回答 默认 最新

  • dongyan6235 2018-05-13 14:47
    关注

    This did the trick, now queries work from PHP as well :

    SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
    

    (or don't turn on STRICT_TRANS_TABLES).

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

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢