It is necessary to insert records into the table in a loop. The logic is that the same order identifier is inserted into the OrderID field, and the identifiers of all products added to the order into the ProductID field. I'm trying this:

 $ids=array_keys($productsInCart); for ($i=0;$i<count($ids);$i++){ $query ="INSERT INTO tblOrderProduct (OrderID,ProductID) VALUES('$orderid','$ids')"; $mysqli->query($query); } 

The $productsInCart array contains product IDs and their quantity, respectively. In general, it does not work, tell me what's wrong.

  • 3
    Probably should have used $ ids [$ i] in the query or something like that ... - Mike
  • @Mike really overlooked! Thank you very much! - Denis

1 answer 1

With your permission, I would suggest that you use the multiline INSERT operator, so you can insert records in one call, rather than a set in a loop

 <?php $ids = array_keys($productsInCart); $sql = array(); for ($i = 0; $i < count($ids); $i++) { $sql[] = "('$orderid', '{$ids[$i]}')"; } if(count($sql) > 0) { $query = "INSERT INTO tblOrderProduct (OrderID, ProductID) VALUES " . implode(",", $sql); $mysqli->query($query); } 
  • Check the brackets, in appearance you have closing more than opening. The syntax should be insert into tab (f1,f2) values (1,1),(1,2),(1,3) - Yura Ivanov
  • @YuraIvanov, thanks, corrected. - cheops
  • thanks, come in handy! - Denis