简体   繁体   中英

Issue with bulk insert in mysql using pdo and php

I am trying to insert bulk records in mysql using pdo but for some reason I am not able to build up the query.

My POST looks like this

Array
(       
    [ques_1] => dsadasd
    [ques_2] => 5
    [ques_3] => dasdsad
    [ques_4] => 23/7/2014
    [savecontinue] => Save & Continue
)

My desired array should look like this

Array
(        
    [quid] => 1        
    [answer] => dasdsad
)
Array
(        
    [quid] => 2       
    [answer] => on
)
Array
(       
    [quid] => 3       
    [answer] => dasdsad
)
Array
(        
    [quid] => 4        
    [answer] => 23/7/2014
)

My code looks like this

foreach($_POST as $k=>$v)
{
    if($k != 'savecontinue' and  $k != 'skipsave')
    {
        list(,$qid) = explode("_",$k);
        $insertData[$qid]  = $v;

    }
}

$sql = "INSERT INTO answers (quid, answer)
        VALUES (:quid, :answer)";
$query = $this->db->prepare($sql);
$query->execute($insertData);

The error is PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Note: I have simplified/reduced the query params and code for better understanding.

Well it seems to me that you would be better of with something like this.

You also were passing to many parameters to the INSERT, the array you pass must have only those values required by the query and be named with the ':' in front.

// prepare the query for multiple use later
$sql = "INSERT INTO answers (userid, catid, quid, qstep, answer)
        VALUES (:userid, :catid, :quid, :qstep, :answer)";
$query = $this->db->prepare($sql);

// create an array of inputs
for ($x=1; $x < 5; $x++ ) {
    $insertData[]  = array( ':userid' => 1,
                            ':catid'  => $_POST['catid'],
                            ':quid'   => $x,
                            ':qstep'  => 1,
                            ':answer' => $_POST['ques_'.$x]);  
}

// loop over the array of inputs 
foreach ( $insertData as $data ) {
    $query->execute($data);
}

Change the following:

$insertData  = array("$qid"=>"$v");

to:

$insertData[$qid] = $v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM