嗨,大家經過幾次試驗和研究仍然無法做到這一點。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表中插入多個數據?
hi nouphal!哇!它的工作!你的真棒!但問題是,當插入發生在數據庫中,我輸入兩個值的四個領域,所以它給了我像item1 descp1 qty1 amount1和空白項目空白desc空白數量空白量和item2 desc2 qty2 amount2 >> >>你可以看到它插入了兩個數據,但它給了我一個空白數據,所以它插入了3個數據,item1空白項目和item3 – user3114394