Insert multiple items into one ID MySQL from check

2020-04-01 07:31发布

问题:

I badly needed this solution. Here is the image what I will checked:

Here is a Order Id. it will common to all problem Title.

Which will insert like that:

Here is the code I use:

  if(isset($_POST['Submit'])){
    try{
    $orderNo = $_SESSION['orderNo'];
    $serviceTitle=$_POST['serviceTitle'];
    $price= $_POST['price'];    
    $quantity= $_POST['quantity'];  
    $amount= $_POST['amount'];

    for ($i=0; $i<count($serviceTitle); $i++){
        $statement = $db->prepare("INSERT INTO invoice (orderNo,productName,price,quantity,amount) VALUES (?,?,?,?,?)");
        $statement->execute(array($orderNo,$serviceTitle[$i],$price[$i],$quantity[$i],$amount[$i]));
    }

    header("location: order_confirm_tech_step1.php");
    }
    catch(Exception $e) {
            $error_message = $e->getMessage();
    }
}

and every array input I use like: name="serviceTitle[]". Thanks in Advance.

回答1:

why not you try this, check if checkbox is checked before executing query

if(isset($_POST['Submit'])){
    try{
    $orderNo = $_SESSION['orderNo'];
    $serviceTitle=$_POST['serviceTitle'];
    $price= $_POST['price'];    
    $quantity= $_POST['quantity'];  
    $amount= $_POST['amount'];

    for ($i=0; $i<count($serviceTitle); $i++){
       if(!empty($_POST['checkbox'][$i])) {
            $statement = $db->prepare("INSERT INTO invoice (orderNo,productName,price,quantity,amount) VALUES (?,?,?,?,?)");
            $statement->execute(array($orderNo,$serviceTitle[$i],$price[$i],$quantity[$i],$amount[$i]));
        }
    }

    header("location: order_confirm_tech_step1.php");
    }
    catch(Exception $e) {
            $error_message = $e->getMessage();
    }
}

Note : name="checkbox[]"