2013-12-20 88 views
1

嗨,大家經過幾次試驗和研究仍然無法做到這一點。PDO如何從數組中插入多個數據到數據庫?

我得到這個數組:

<td><textarea name="item[]" value=""></textarea></td> 
<td><textarea name="description[]" value=""></textarea></td> 
<td><input type="text" name="qty[]" value="" /></td> 
<td><input type="text" name="amount[]" value="" /></td> 

,我的方法是在這裏:

public function insertRecord($param1, $param2, $param3, $param4, $args1, $args2, $args3, $args4) { 

    $query = $this->db->prepare('INSERT INTO `request_to_purchase` (`requestedby`, `date`, `jobtitle`, `supervisor`, `notes`) VALUES (?, NOW(), ?, ?, ?)'); 

    $query->bindValue(1, $param1, PDO::PARAM_STR); 
    $query->bindValue(2, $param2, PDO::PARAM_STR); 
    $query->bindValue(3, $param3, PDO::PARAM_STR); 
    $query->bindValue(4, $param4, PDO::PARAM_STR); 

    try { 

     $query->execute(); 

     $lastIDInserted = $this->db->lastInsertId(); 

     $row = $query->rowCount(); 

     if(count($row) > 0) {    
      $this->insertItem($lastIDInserted,$args1, $args2, $args3, $args4); 
     } else {     
      return false; 
     } 

    } catch(PDOException $e) { 

     die($e->getMessage()); 

    } 

} 

public function insertItem($arg1, $arg2, $arg3, $arg4, $arg5) { 



    $query = $this->db->prepare('INSERT INTO `ordered_item` (`rtp_id`, `item`, `description`, `qty`, `amount`, `date`) VALUES (?, ?, ?, ?, ?, NOW())'); 

    $query->bindValue(1, $arg1); 
    $query->bindValue(2, $arg2); 
    $query->bindValue(3, $arg3); 
    $query->bindValue(4, $arg4); 
    $query->bindValue(5, $arg5); 

    try { 

     $query->execute(); 

     $row = $query->rowCount(); 

     if(count($row) > 0){ 
      return true; 
     }else { 
      return false; 

     } 
    } catch(PDOException $e) { 
     die($e->getMessage()); 
    } 

} 

我曾經有四個迴路,我認爲這是一種錯誤的做法。

for($a = 0; $a < count($item); $a++) { 

    $test1 = $item[$a]; 
} 

for($b = 0; $b < count($description); $b++) { 

    $test2 = $description[$b]; 
} 

for($c = 0; $c < count($qty); $c++) { 

    $test3 = $qty[$c]; 
} 

for($d = 0; $d < count($amount); $d++) { 

$test4 = $amount[$d]; 
} 

如何在ordered_item表中插入多個數據?

回答

1

假設 $args1= $_POST['item'],$args2 = $_POST['description'],$args2 = $_POST['qty'],$args2 = $_POST['amount']的數組值然後更改以下部分如下:

if(count($row) > 0) {    
     $argsLen = sizeof($args1); 
     for($i=0;$i<$argsLen;$i++){ //loop array and insert 
      $this->insertItem($lastIDInserted,$args1[$i], $args2[$i], $args3[$i], $args4[$i]); 
     } 
    } else {     
     return false; 
    } 

我希望這可以幫助你

+0

hi nouphal!哇!它的工作!你的真棒!但問題是,當插入發生在數據庫中,我輸入兩個值的四個領域,所以它給了我像item1 descp1 qty1 amount1和空白項目空白desc空白數量空白量和item2 desc2 qty2 amount2 >> >>你可以看到它插入了兩個數據,但它給了我一個空白數據,所以它插入了3個數據,item1空白項目和item3 – user3114394

0

要你應該改變的第一個值後仍無法解決空白插入的問題for循環在$ i檢測到限制之前增加$ i,似乎它是第一次將$ i設置爲0時進行比較,因此請嘗試將其更改爲:

for ($i = 0; $i < $argsLen; ++$i) 

希望這會有所幫助。

相關問題