简体   繁体   中英

PHP foreach loop with multiple index variables

Can anyone see what is wrong with the following code?

I'm trying to carry out a foreach loop on 2 arrays from a form.

Form Code:

<td>
<input type="checkbox" name="PR[]" value="DP01">Version 1 Daypack - $55.00<br/>
<input type="checkbox" name="PR[]" value="DP02">Version 2 Daypack - $30.00<br/>
</td>
<td>
<input type="text" name="QTY[]" size = "2"/><br/>
<input type="text" name="QTY[]" size="2"/><br/>
</td>

PHP Code:

if(!empty($_POST['PR']))
{
    foreach (array_combine($_POST['PR'], $_POST['QTY']) as $PRS => $QTYS)
    {
            $sql="INSERT INTO ORDER_TBL (TRANSACTION_ID, CUSTOMER_ID, PRODUCT_ID, QUANTITY)
            VALUES ('','$_SESSION[user]','$PRS,'$QTYS)";

        if (!mysqli_query($con,$sql))
        {
            die('Error: ' . mysqli_error($con));
            exit;
        }
    }
}

This way is not really good at all. The textfields will be posted not matter if they're empty or has content, while the checkboxes only is posted when checked. This will cause the arrays to be of different length and array_combine will fail.

Do a print_r($_POST) and you'll see what input is posted.

And that's not even considering the security nightmare this will create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM