0

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.

1
  • 1
    bindParam takes a reference to a variable as its argument, bindValue takes the value of a variable as its argument. The way you did it, you gave it multiple references to the same variable $val, which will of course all evaluate to the same value. Commented Jul 26, 2012 at 16:03

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sometimes we miss those simple things that make the most difference in our lives. Thank you both for your ultra fast responses. You saved my day.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.