Ravi
Ravi

Reputation: 877

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.

Upvotes: 0

Views: 873

Answers (1)

Robert
Robert

Reputation: 8767

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

Upvotes: 2

Related Questions