我认为它应该是可能的,但我不知道如何写它。
两个语句都应该保存在同一个表格行中。
这是我的代码:
foreach($_POST["checkbox"] as $id){
$query ="INSERT INTO table2 (name, number, price, quantity, sumPrice, supplier, customer)
SELECT name, number, price, quantity, sumPrice, supplier, customer
FROM table1
WHERE table1_id = '".$id."'";
"INSERT INTO table2(adoptedBy)
VALUES ('$name')";
$result = mysqli_query($db_link, $query);
我错了什么?
答案 0 :(得分:0)
因此,您首先要使用INSERT插入一个新行,然后更新“已采用的”'带有新价值的字段。
示例:
"UPDATE table2 SET adoptedBy='$name' WHERE --Here you refer to the row's primary id";
在WHERE子句之后,您只是以某种方式识别您的行(例如,主要ID,未在OP中显示)
答案 1 :(得分:0)
第一条陈述:从table1中选择多个数据并将其复制到 表2。
您需要使用效果良好的INSERT INTO SELECT。
$query ="INSERT INTO table2 (name, `number`, price, quantity, sumPrice, supplier, customer)
SELECT name, `number`, price, quantity, sumPrice, supplier, customer
FROM table1
WHERE table1_id = '".$id."'";
第二条陈述:将变量保存到table2。
你没注意到的一件事是WHERE table1_id = '".$id."'";
之后你终止了$query
因此它永远不会运行`
"INSERT INTO table2(adoptedBy)
VALUES ('$name')";
您可以做的是使用mysqli_multi_query();
然后你的查询将是:
<?php
$query = "INSERT INTO table2 (name, `number`, price, quantity, sumPrice, supplier, customer)
SELECT name, `number`, price, quantity, sumPrice, supplier, customer
FROM table1
WHERE table1_id = '" . $id . "';";
$query .= "UPDATE table2 SET adoptedBy =".$name." where id = LAST_INSERT_ID()";
$result = mysqli_multi_query($db_link, $query);
if ($result) {
echo "success";
} else {
echo "Error : " . mysqli_error($db_link);
}
?>
希望这有帮助。
注意:无论您使用的是using prepared statements还是mysqli prepared语句,我都建议您开始学习SQL查询pdo prepared
编辑:
如果上述建议不起作用,则替代
当第一个查询成功运行时,您可以更新LAST_INSERT_ID()获取最后一个插入的ID,然后对该ID进行更新
<?php
$query = "INSERT INTO table2 (name, `number`, price, quantity, sumPrice, supplier, customer)
SELECT name, `number`, price, quantity, sumPrice, supplier, customer
FROM table1
WHERE table1_id = '" . $id . "';";
$result = mysqli_query($db_link, $query);
if ($result) {
$query = "UPDATE table2 SET adoptedBy ='".$name."' WHERE id = LAST_INSERT_ID();";
if(mysqli_query($db_link,$query)){
echo "success";
}else{
echo "update failed".mysqli_error($db_link);
}
} else {
echo "Error : " . mysqli_error($db_link);
}
?>