简体   繁体   中英

Inserting multiple rows with PHP PDO

I'm trying to insert multiple rows using transaction-bind through PHP PDO. Below is my code.

$arrkeys = array_keys($this->postItem);
$itemqry = "INSERT INTO test_item (itemdate, flditmname, fieldtype, subscribe, id, year) VALUES (:itemdate, :flditmname, :fieldtype, :subscribe, :id, :year);" // dynamically generated

$itmstmt = $dbcon->prepare($itemqry);

for ($i=0; $i<$cnt; $i++){
  foreach ($arrkeys as $key){
     $val = $this->postItem[substr($key,1)][$i];
     $itmstmt->bindParam($key, $val);
  }

  try {
    $itmstmt->execute();
  } catch (PDOException $e){
    echo $e->getMessage();
  }

}

I verified the values are populating correctly (for the bind) as follows :

echo $key."=".$val."<br>";  //echoed just before the bind.

:itemdate=2012-07-02 15:09:04
:flditmname=dccd
:fieldtype=2
:subscribe=X
:id=12345
:year=2012
:itemdate=2012-07-12 15:09:19
:flditmname=lkpok
:fieldtype=3
:subscribe=X
:id=12345
:year=2012

However, after inserting in my db table, all fields of all rows are taking the value '2012' (the value of last field).

I get no clue why this is happening. Can anyone help me track the issue? Thank you very much for your time.

You are using the wrong method:

$itmstmt->bindParam($key, $val); 

Should be:

$itmstmt->bindValue($key, $val); 

bindValue binds a value to a parameter, whereas bindParam binds a parameter to the specified variable name

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