Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
        }
    }
}
share|improve this question
1  
Security advise: Escape all user input. Read about sql injection. –  Zsolt Szilagy May 31 '13 at 11:01
    
Is $TGS defined elsewhere? this would lead to nul value for Product_Id perhaps. What is going wrong with this - how does the output vary from what is expected? error codes? - also the SQL is wrong - '$TGS,'$QTYS should be '$TGS','$QTYS' –  Robert Seddon-Smith May 31 '13 at 11:02
    
You are not executing the query. And what is the point of using array_combine if you are not using the keys anyway? –  jah May 31 '13 at 11:03
1  
@ZsoltSzilagy here is a nice image to represent that: xkcd.com/327 –  imulsion May 31 '13 at 11:04
    
@RobertSeddon-Smith Typo, iv'e edited the code above. –  cs91 May 31 '13 at 11:05

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
if we don't worry about the security issues or the error handling will it still run when inputted correctly? –  cs91 May 31 '13 at 11:15
    
@cs91 Problem is that if one of the checkboxes is not checked, it wont be sent, and then your array_combine will fail. –  jah May 31 '13 at 11:17
    
@cs91 You will need to check both boxes for the array_combine to not fail, but if both boxes are checked it should pass and create the sql. Test running the query generated to see if it's correct in cooperation with your database –  Sondre May 31 '13 at 11:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.