简体   繁体   English

PHP MYSQL-插入新记录,但需要另一个表中的select语句中的列-PHP中失败

[英]PHP MYSQL - insert a new record but requires column from select statement in another table - fails in php

I am trying to add a record in a table through a php form. 我正在尝试通过php表单在表中添加一条记录。 One of the required fields needs to be selected from another table and added into the insert statement before execution. 在执行之前,需要从另一个表中选择一个必填字段并将其添加到insert语句中。

Here is the mysql code, this works perfectly fine in Workbench by getting the 'Select' part and including it the 'Insert' all at the same time. 这是mysql代码,在Workbench中,通过获取“选择”部分并将其同时包含“插入”,可以完美地工作。 My php form returns an error saying that the 'serial' value is null so the 'ADD' fails. 我的php表单返回一个错误,指出'serial'值为null,因此'ADD'失败。

Here is the working mysql - 这是正常工作的mysql-

INSERT INTO table_1 
(type, version, regn, comments, serial)
VALUES ('797', '109F','KILO','new entry', (SELECT serial  
FROM table_2 WHERE consno = '999999'))

As someone who is very new to this I recall reading something along the lines of multiple statements not being possible from within php, any advice or direction on how I can get this 'Insert' to work within php would be much appreciated? 作为一个对此非常陌生的人,我记得在php中无法通过多条语句进行阅读,因此,对于如何使此“插入”在php中工作的任何建议或指导将不胜感激?

Thanks 谢谢

You're doing it wrong. 你这样做是错的。 You need the INSERT ... SELECT pattern. 您需要INSERT ... SELECT模式。

 INSERT INTO table_1 
             (type, version, regn, comments, serial)
 SELECT '797', '109F','KILO','new entry', serial  
   FROM table_2 
  WHERE consno = '999999'

You write a SELECT statement matching the columns you want to insert. 您编写与要插入的列匹配的SELECT语句。 Then you put your INSERT statement right before it. 然后,将INSERT语句放在前面。 The trick here is to specify constants when you need them, and columns from the table where those are needed. 这里的技巧是在需要常量时指定常量,并在表中需要常量的列中指定常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM