我在一个表中插入了一些带有值的字符串,在数据库中将其称为table_1
,现在我想将其插入到SQL数据库的table_2
的单独行中。
$sql = 'INSERT INTO ' . $table_1 . '(shipping_fee, waybill_status, pickup_fee, )
VALUES(:shipping_fee, :waybill_status, :pickup_fee)';
$stmt = $this->dbConn->prepare($sql);
$stmt->bindParam(':shipping_fee', $s_shipping_fee);
$stmt->bindParam(':waybill_status', $s_waybill_status);
$stmt->bindParam(':pickup_fee', $this->pickup_fee);
if($stmt->execute()){ //THIS INSERTED THE STRINGS PERFECTLY
//NOW ALL VALUES TO BE INSERT INTO $sqal is an array
$sqal = 'INSERT INTO ' . $table_2. '(id, waybill_number, client_id, item_name, item_weight, item_length, item_width, item_category, date_added) VALUES(null, :waybill_numberr, :client_idaa, :item_name, :item_weight, :item_length, :item_width, :item_category, :date_added)';
$stmtaaa = $this->dbConn->prepare($sqal);
$stmtaaa->bindParam(':item_name', $this->item_name); //ARRAY
$stmtaaa->bindParam(':item_weight', $this->item_weight); //ARRAY
$stmtaaa->bindParam(':item_length', $this->item_length); //ARRAY
$stmtaaa->bindParam(':item_width', $this->item_width); //ARRAY
$stmtaaa->bindParam(':item_category', $this->item_category); //ARRAY
$stmtaaa->execute(); //HoW do I go about this.
} else {
echo "Could not insert";
exit();
}
答案 0 :(得分:2)
您在第一个查询中遇到语法错误,列或值列表中不应包含尾随逗号,
。
您可以通过使用不同的值多次执行prepare来插入数组。此示例假定您所有的数组都按数字索引(从零到向上)。
上面的代码示例还绑定了比绑定更多的列,因此您需要为每个列绑定一个值。 waybill_numberr
,client_idaa
和date_added
缺少其绑定(我刚刚添加了一些随机占位符)。
$sql = "INSERT INTO $table_1 (shipping_fee, waybill_status, pickup_fee)
VALUES (:shipping_fee, :waybill_status, :pickup_fee)";
$stmt = $this->dbConn->prepare($sql);
$stmt->bindParam(':shipping_fee', $s_shipping_fee);
$stmt->bindParam(':waybill_status', $s_waybill_status);
$stmt->bindParam(':pickup_fee', $this->pickup_fee);
if ($stmt->execute()) {
$sqal = "INSERT INTO $table_2 (id, waybill_number, client_id, item_name, item_weight, item_length, item_width, item_category, date_added)
VALUES (null, :waybill_numberr, :client_idaa, :item_name, :item_weight, :item_length, :item_width, :item_category, :date_added)";
$stmtaaa = $this->dbConn->prepare($sqal);
foreach ($this->item_weight as $key => $value) {
$stmtaaa->execute(["waybill_numberr" => '1', // Change this to your actual value
"client_idaa" => '1', // Change this to your actual value
"item_name" => $value,
"item_weight" => $this->item_weight[$key],
"item_length" => $this->item_length[$key],
"item_width" => $this->item_width[$key],
"item_category" => $this->item_category[$key],
"date_added" => '1']);
}
} else {
echo "Could not insert";
exit();
}