简体   繁体   English

使用准备好的语句插入多行

[英]Insert multiple rows using a prepared statement

I am trying to use the prepared statement query to insert multiple rows in to a table. 我正在尝试使用准备好的语句查询在表中插入多行。 I need to retrieve 2 values from a second table and insert them along with 3 parameters. 我需要从第二个表中检索2个值,并将它们与3个参数一起插入。

MySQL only sees the sub query as a single value not the 2 retrieved so asks for a further parameter to be added as only four are present. MySQL仅将子查询视为单个值,而不是检索到的2,因此由于只有四个,因此要求添加另一个参数。

$stmt = $mysqli->prepare("INSERT INTO tbl_permit_daily_sign_off (permit_id, shift, employee_id, sign_off_date, type)
                              VALUES ((SELECT tbl_permit_project.permit_id, tbl_shifts.shift_name FROM tbl_permit_project
                              INNER JOIN tbl_shifts ON tbl_permit_project.project_id = tbl_shifts.project_id
                            WHERE tbl_shifts.end_time <= NOW()), ?, ?, ?)");
$stmt->bind_param("iss",  $permit_employee = 0, $today, $type = "auto");
$stmt->execute();
$stmt->close();

You need the INSERT ... SELECT form of insert, not the INSERT ... VALUES() form. 您需要INSERT ... SELECT形式,而不是INSERT ... VALUES()形式。

INSERT INTO tbl_permit_daily_sign_off 
            (permit_id, shift, employee_id, sign_off_date, type)
     SELECT tbl_permit_project.permit_id, tbl_shifts.shift_name  
      FROM tbl_permit_project
INNER JOIN tbl_shifts ON tbl_permit_project.project_id = tbl_shifts.project_id
     WHERE tbl_shifts.end_time <= NOW()), ?, ?, ?)

How does this work? 这是如何运作的?

1) you design a SELECT query giving the columns you want to use in your INSERT query. 1)设计一个SELECT查询,提供要在INSERT查询中使用的列。 Then you test and troubleshoot it. 然后,您对其进行测试并进行故障排除。

2) You put INSERT INTO tbl (col, col, col...) right before your SELECT. 2)您将INSERT INTO tbl (col, col, col...)放在SELECT之前。

Your INSERT chooses the columns (permit_id, shift, employee_id, sign_off_date, type) but your SELECT only mentions two of those columns. INSERT选择列(permit_id, shift, employee_id, sign_off_date, type)但是SELECT仅提及其中两列。 You need the SELECT to mention all five. 您需要SELECT才能提及全部五个。

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

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