2013-03-26 3 views
-2

이 중첩 된 foreach 루프를 작동 시키려고하는데 행운이 없었습니다. 여기 내 코드가있다.중첩 된 foreach 루프 문제

$q = 0; 
$arrayCountTwo = count($_POST['quantity']); 
$i = 0; 
$arrayCountThree = count($_POST['items']); 
foreach ($_POST['items'] as $items) { 
    $sql = ''; 
    foreach ($_POST['quantity'] as $quantity) { 
     $q++; 
     if ($q > $arrayCountTwo) { 
      break; 
     } else { 
      $sql .= "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$items."','".$startDate."', '".$endDate."','".$quantity."')"; 
     } 
     var_dump($sql); 
    } 
} 

그것은 내게 각 반복에 $items 어레이 내의 제 1 값을주는 유지한다. 이 문제를 어떻게 해결할 수 있습니까?

여기에 요청한 배열이 있습니다.

items 배열과 수량 배열을 순서대로 사용합니다.

array(3) { 
    [0]=> 
    string(2) "11" 
    [1]=> 
    string(1) "6" 
    [2]=> 
    string(1) "2" 
} 

array(3) { 
    [0]=> 
    string(1) "1" 
    [1]=> 
    string(1) "2" 
    [2]=> 
    string(1) "1" 
} 

매번 이렇게해야합니다.

INSERT INTO `ts_table` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('11','2013-4-11', '2013-4-25','1') 

INSERT INTO `ts_table` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('6','2013-4-11', '2013-4-25','2') 
+0

다른 작업을 수행하기 전에 코드에 SQL 주입 취약점이있는 것 같습니다. –

+1

나는 SQL 문제를 알고있다. 난 그냥 내 로컬 환경에서 루프를 일하고 싶습니다. – wowzuzz

+1

'items'과'quantity' 배열을 보여 주시겠습니까? – MichaelRushton

답변

2

이것은 당신이 원하는 일을해야합니다

foreach ($_POST['items'] as $key => $items) 
{ 
    $sql = "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$items."','".$startDate."','".$endDate."','".$_POST['quantity'][$key]."')"; 
    echo $sql . '<br>'; 
} 
+0

이 루프 내에서 그런 수량을 반복 할 수 있는지 알지 못했습니다. MichaelRushton을 잘 알고 있습니다. 모든 도움을 주셔서 감사합니다! – wowzuzz

0
for($i = 0, $iMax = min(count($_POST['items']), count($_POST['quantity'])); $i < $iMax; $i++) 
{ 
    $sql .= "INSERT INTO `trade_show_reserved` (ProductID, DateReserved, DateReservedEnd, QuantityReserved) VALUES ('".$_POST['items'][$i]."','".$startDate."', '".$endDate."','".$_POST['quantity'][$i]."')"; 
} 

는 당신이 필요로의 라인을 따라 더 많은 것이다.

0

나는이 같은 뭔가를 찾고있다 생각합니다. item[1]quantity[1]이 서로 관련된다고 가정하십시오.

foreach ($_POST['items'] as $idx => $item) { 
    // get the quantity with the same index as the item 
    // if it does not exist, default to zero 
    $quantity = isset($_POST['quantity'][$idx]) ? $_POST['quantity'][$idx] : 0; 

    // insert query... 

}