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.
bindParamtakes a reference to a variable as its argument,bindValuetakes 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.