PDO如何从数组中将多个数据插入数据库?

时间:2013-12-20 02:39:15

标签: php mysql 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表上插入多个数据?

2 个答案:

答案 0 :(得分: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;
    }

我希望这有助于你

答案 1 :(得分:0)

要解决第一个值之后的空白插入问题,你应该更改for循环以增加$ i,然后再检查它是否超出限制,好像是在第一次比较时,$ i仍然设置为0,所以尝试将其更改为:

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

希望这会有所帮助。