0

I am trying to make a loop for 2 arrays and I run into conflicts where it creates duplicate entries...I figure I am just creating the loop wrong.

        foreach($productIds as $productID){

            foreach($qty as $q) {
$sql = "INSERT INTO orderedProducts (productID, orderID, qty) VALUES 
((select productID from products where productID ='$productID'), '$orderID', '$q')";
           execute_query($sql);

                 }
           }

If I remove the qty loop and just hardcode the qty in it works fine. Is there some sort of way to combine the two loops?

Butterflycode
  • 759
  • 2
  • 10
  • 23

2 Answers2

1

use INSERT INTO...SELECT statement on this,

INSERT INTO orderedProducts (productID, orderID, qty) 
SELECT productID, '$orderID', '$q'
FROM   products
WHERE  productID = '$productID'

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

Figured out the problem...can't use foreach loops it just messes up, I just used the index's of the arrays

    for($i =0 ; $i < sizeof($productIds);$i++){ 
$sql = "INSERT INTO orderedProducts (productID, orderID, qty) VALUES ((select productID from products where productID ='$productIds[$i]'), '$orderID', '$qty[$i]')";
        execute_query($sql);
       }
Butterflycode
  • 759
  • 2
  • 10
  • 23