数据未使用 PDO 中的数组 foreach 函数插入数据库 PHP

data not inserting in DB using array foreach function in PDO PHP

当我使用不同的输入和相同的名称将数据发送到 PHP 中的服务器时,我无法通过 foreach 函数插入到我的数据库中。 我尽了最大努力,Whosebug 上提供了所有其他功能,但它们对我都没有帮助。

请帮助我如何进行此修复以及实现我的代码功能的真正代码是什么。 因为开发者控制台发送数据是 -

productID: 21202,33201,44202,44202,33204

Qty: 1,2,3,4,5

PHP

foreach($_POST['productID'] as $product) {
   foreach($_POST['Qty'] as $qty) {
      $stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
      $stmt->execute(array(
       ':p' => $product,
       ':q' => $qty 
      ));
   }
}

echo $_POST['productID'];
response is = 21202,33204,332061

您的输入数据似乎是逗号分隔的值字符串,而不是数组。要迭代它们,您需要使用 explode:

将它们转换为数组
$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
foreach(explode(',', $_POST['productID']) as $product) {
   foreach(explode(',', $_POST['Qty']) as $qty) {
      $stmt->execute(array(
       ':p' => $product,
       ':q' => $qty 
      ));
   }
}

请注意,您只需要准备一次语句,所以我已将其移出循环。还可以通过在循环外绑定参数进一步优化这段代码:

$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
$stmt->bindParam(':p', $product);
$stmt->bindParam(':q', $qty);
foreach(explode(',', $_POST['productID']) as $product) {
   foreach(explode(',', $_POST['Qty']) as $qty) {
      $stmt->execute();
   }
}

请注意,上面的代码会将 productIDQty 值的所有组合插入到 table 中(就像您的原始代码一样),但您可能只需要匹配的值.在这种情况下,请使用此代码:

$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
$stmt->bindParam(':p', $product);
$stmt->bindParam(':q', $qty);
$quantities = explode(',', $_POST['Qty']);
foreach(explode(',', $_POST['productID']) as $key => $product) {
    $qty = $quantities[$key];
    $stmt->execute();
}