0

我有三个变量($product_id、$size_id、$quantity),它们从“form”获取并插入到 pending_order 表中。所以我使用 array_combine 函数来组合三个变量,而不是使用每个循环来插入多条记录。但它显示一个错误

“警告:array_combine() 需要 2 个参数,3 个给定”。

所以我完全卡住了,是否有任何其他方法可以在数组中传递这三个变量,而不是使用每个循环来插入记录。

<form method="post" action="">

<input type="hidden" name="ip_address" value="<?php echo $ip_address; ?>">   
<input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>">   
<input type="hidden" name="size_id[]" value="<?php echo $size_id; ?>"> 
<input type="hidden" name="quantity[]" value="<?php echo $quantity; ?>" >
<input type="submit"  name="submit" value="Confirm Your Order"> 

</form>

<?php
if (isset($_POST['submit'])) {
$product_id = $_POST['product_id'];
$size_id = $_POST['size_id'];
$ip_address = $_POST['ip_address'];
$quantity = $_POST['quantity'];

$array = array_combine($product_id, $size_id, $quantity);

foreach ($array as $h => $v) {

$insert_pending = "INSERT INTO pending_orders 
(cus_id,product_id,size_id,quantity,ip_address) VALUES 
('$cus_id','$h','$v','$quantity','$ip_address')";

 $run2 = mysqli_query($con, $insert_pending);

 }

if($run2===true){

 echo "<script>window.open('thanku.php','_self')</script>";
  }else{
 echo "<script>alert('Sorry, Try Again')</script>";

 }


 }
4

1 回答 1

1

您可以只循环其中一个数组,使用该数组中的索引来访问其他数组中的相应值:

foreach ($product_id as $index => $h) {
    $v = $size_id[$index];
    $q = $quantity[$index];
    $insert_pending = "INSERT INTO pending_orders 
                            (cus_id,product_id,size_id,quantity,ip_address) VALUES 
                            ('$cus_id','$h','$v','$q','$ip_address')";
    $run2 = mysqli_query($con, $insert_pending);
}

请注意,$run2只会有最后一次INSERT查询的状态。所以如果他们都失败了,但最后一个你不会知道。您可能想尝试在查询后将其添加到循环中:

if (!$run2) break;

然后在您的错误消息中,您可以指出哪个插入失败,例如

echo "<script>alert('Insert failed for id $cus_id on data $h, $v, $q')</script>";
于 2019-05-23T00:14:02.310 回答