0

我正在尝试通过 PHP PDO 使用事务绑定插入多行。下面是我的代码。

$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();
  }

}

我验证了值是否正确填充(用于绑定),如下所示:

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

但是,在我的 db 表中插入后,所有行的所有字段都采用值“2012”(最后一个字段的值)。

我不知道为什么会这样。谁能帮我跟踪问题?非常感谢您的宝贵时间。

4

1 回答 1

3

您使用了错误的方法:

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

应该:

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

bindValue将值绑定到参数,而 bindParam将参数绑定到指定的变量名

于 2012-07-26T16:32:21.360 回答