0

I need some help with nested foreach.

This is my code:

$program = $_POST['program'];
$licence = $_POST['licence'];
    foreach($program as $p){
        foreach($licence as $l){
mysql_query("INSERT INTO programs (pcname, program, licence) VALUES ('". $pcname ."', '". $p ."', '". $l ."')");

  }
}

This doesn't work and I know why. But I cannot find a way to fix the issue. The issue is, that it is going through all the values in the inside foreach, then is is going through them all, all over again for the next value in the outside foreach.

This probably wasn't explained very well, but hopefully you can understand what I am doing in trying to achieve, and to help me out.

3
  • What behavior do you expect, or want? Commented Apr 11, 2013 at 19:26
  • Is the $program/$licence an array? I think not, as the $_POST values are strings. Commented Apr 11, 2013 at 19:27
  • @Voitcus they are arrays, and not strings. Commented Apr 11, 2013 at 19:54

2 Answers 2

2

Assuming your two arrays have a 1:1 mapping between their elements, say. 5 each, then your nested loops are going to produce 25 insert calls. You need to use the keys from one array to refer to the other:

foreach($program as $key => $p) {
    $l = $license[$key];
    mysql_query(...);
}

and note that you are WIDE open for sql injection attacks.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked like a charm, worked exactly as I wanted it to, and yes I know I am open to attacks, but this is only for local use, and I will be added this kinda stuff in once it has all the functionality. Thanks again for your answer :)
$l = array_shift(license); If the keys aren't the same.
0

correct me if I am wrong but I believe your problem would be solved by simply moving your query statement to after the first for loop...

Comments

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.