1

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;
        }
    }
}
6
  • 1
    Security advise: Escape all user input. Read about sql injection. Commented May 31, 2013 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' Commented May 31, 2013 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? Commented May 31, 2013 at 11:03
  • 1
    @ZsoltSzilagy here is a nice image to represent that: xkcd.com/327 Commented May 31, 2013 at 11:04
  • @RobertSeddon-Smith Typo, iv'e edited the code above. Commented May 31, 2013 at 11:05

1 Answer 1

1

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.

3
  • if we don't worry about the security issues or the error handling will it still run when inputted correctly? Commented May 31, 2013 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. Commented May 31, 2013 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 Commented May 31, 2013 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.