如何在准备好的语句php中的不同行中插入多个记录

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (47)

我在一个表中插入了一些带有值的字符串,让table_1我在我的数据库中调用它,现在我有数组,我想table_2在我的SQL数据库中插入单独的行。

$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();
}
提问于
用户回答回答于

您的第一个查询中存在语法错误,,列或值列表中的尾随逗号不应该出现。

您可以通过使用不同的值执行多次准备来插入数组。此示例假定所有数组都按数字索引(从零开始)。

上面的代码示例还绑定了比绑定更多的列,因此您需要将值绑定到每个列。waybill_numberrclient_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();
}

扫码关注云+社区

领取腾讯云代金券