使用PHP PDO插入多行
我试图通过PHP PDO使用事务绑定插入多行。下面是我的代码使用PHP PDO插入多行,php,pdo,prepared-statement,Php,Pdo,Prepared Statement,我试图通过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 ge
$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();
}
}
$arrkeys=array\u key($this->positem);
$itemqry=“插入测试项目(itemdate,flditmname,fieldtype,subscribe,id,year)值(:itemdate,:flditmname,:fieldtype,:subscribe,:id,:year);”//动态生成
$itmstmt=$dbcon->prepare($itemqry);
对于($i=0;$ipostItem[substr($key,1)][$i];
$itmstmt->bindParam($key,$val);
}
试一试{
$itmstmt->execute();
}捕获(PDO$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
echo$key.“=”$val.“
”;//在绑定之前进行了回显。
:itemdate=2012-07-02 15:09:04
:flditmname=dccd
:fieldtype=2
:订阅=X
:id=12345
:年份=2012年
:itemdate=2012-07-12 15:09:19
:flditmname=lkpok
:fieldtype=3
:订阅=X
:id=12345
:年份=2012年
但是,在my db表中插入后,所有行的所有字段都采用值“2012”(最后一个字段的值)
我不知道为什么会发生这种情况。有人能帮我跟踪这个问题吗?非常感谢您抽出时间。您使用了错误的方法:
$itmstmt->bindParam($key, $val);
应该是:
$itmstmt->bindValue($key, $val);
将值绑定到参数,而
将参数绑定到指定的变量名您使用了错误的方法:
$itmstmt->bindParam($key, $val);
应该是:
$itmstmt->bindValue($key, $val);
将值绑定到参数,而
将一个参数绑定到指定的变量名
bindParam
将一个变量的引用作为其参数,bindValue
将一个变量的值作为其参数。按照您的操作方式,您将多个引用给了同一个变量$val
,这当然会计算为相同的值。bindParam
将对变量的引用作为其参数,bindValue
将变量的值作为其参数。您这样做的方式是,您对同一个变量的多个引用$val
,这些引用当然都将计算为相同的值。有时,我们会忽略那些对您的影响最大的简单事情r生命。感谢你们两位的超快反应。你们救了我一天。有时我们会错过那些对我们生活最重要的简单事情。感谢你们两位的超快反应。你们救了我一天。