Reputation: 61
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.
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.
$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();
Upvotes: 0
Views: 269
Reputation: 108641
You need the INSERT ... SELECT
form of insert, not the INSERT ... VALUES()
form.
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. Then you test and troubleshoot it.
2) You put INSERT INTO tbl (col, col, col...)
right before your SELECT.
Your INSERT chooses the columns (permit_id, shift, employee_id, sign_off_date, type)
but your SELECT only mentions two of those columns. You need the SELECT to mention all five.
Upvotes: 1