Search code examples
phpforeacharray-combine

how to Pass 3 arguments in array_combine, is that possible?


i have three variables ($product_id, $size_id, $quantity) which get from "form" and insert into the pending_order table.So i used the array_combine function to combine three variables and than using for each loop to insert the multiple records. but it shows an error

"Warning: array_combine() expects exactly 2 parameters, 3 given".

So im totally stuck, is that any other way to pass these three variables in array and than use for each loop to insert the record.

<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>";

 }


 }

Solution

  • You can just loop through one of the arrays, using the index from that array to access the corresponding values from the other arrays:

    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);
    }
    

    Note that $run2 will only have the status of the last INSERT query. So if they all fail but the last one you won't know. You might want to try adding this to the loop after the query:

    if (!$run2) break;
    

    and then in your error message you can indicate which insert failed e.g.

    echo "<script>alert('Insert failed for id $cus_id on data $h, $v, $q')</script>";