如何在准备好的php语句中在不同的行中插入多条记录
我在数据库中的一个表中插入了一些带值的字符串,称之为如何在准备好的php语句中在不同的行中插入多条记录,php,mysql,arrays,pdo,insert,Php,Mysql,Arrays,Pdo,Insert,我在数据库中的一个表中插入了一些带值的字符串,称之为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); $
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();
}
您在第一个查询中出现语法错误,列或值列表中不应该有尾随逗号
,
可以通过使用不同的值多次执行prepare来插入数组。本例假设所有数组都按数字(从零到零)进行索引
上面的代码示例绑定的列也比绑定的多,因此需要为每一列绑定一个值waybill\u numberr
、client\u idaa
和date\u added
缺少绑定(我刚刚添加了一些随机占位符)
你是在问如何绑定和执行一个数组而不是一个字符串吗?这些数组是如何索引的?从0到n编号的?@qirel是的,这个问题是这样的。@qirel我已经绑定了第一个准备执行的数组statement@qirel,是,当我打印(项目名称)时,数组从0向上
$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();
}