[英]MySQL Trigger not working in PHP
TL;DR: Query works from MySQL CLI but NOT from PHP, as if the triggers were not fired by PHP. TL; DR:查询不能从MySQL CLI进行,而不能从PHP进行,就像触发器不是由PHP触发一样。
I have a mySQL structure which looks like this: 我有一个mySQL结构,如下所示:
entity
is the "parent" table with id
as PK entity
是id
为PK的“父”表 contact
is a "child" table with entity_id
as PK and FK on entity
contact
是一个“ child”表, entity_id
为entity
上的PK和FK person
is a "grand-child" table with entity_id
as PK and FK on contact
person
是一个“大孩子”表entity_id
作为PK和FK的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
. 我创建了一些触发器,以便当我在
contact
插入新行时,它首先在entity
插入新行并将新的id
用作entity_id
。 Idem for person
and contact
. 同上用于
person
和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 id
s. 因此,例如,当我
person
插入新行时,第一个触发器创建了一个contact
行,该行通过第二个触发器在entity
创建了一个行,所有行都具有匹配的id
。
This WORKS in MySQL but NOT in PHP. 这在MySQL中起作用,但在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: 在mySQL CLI中工作(创建并匹配所有行),但是在PHP7中使用
mysqli->query()
调用时失败,并显示错误:
Field 'entity_id' doesn't have a default value
How can I make it work in PHP as well? 如何使它在PHP中也能正常工作? Or do I have to go through the process of creating all parent tables manually?
还是我必须经历手动创建所有父表的过程?
This did the trick, now queries work from PHP as well : 这样就成功了,现在查询也可以从PHP进行:
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
(or don't turn on STRICT_TRANS_TABLES
). (或不要打开
STRICT_TRANS_TABLES
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.