【发布时间】:2015-12-27 00:33:06
【问题描述】:
我有一个 PHP 关联数组,我想在 foreach 循环中将其值与 PDO 绑定。到目前为止,我有这个:
$sqlSecondaryInsert = "INSERT INTO TCMS_Documents ";
// Table Fields
$sqlSecondaryFields = " (DocumentID, ";
$sqlSecondaryValues = "VALUES (:lastDocumentInsertID, ";
foreach ($intersectArray as $key => $value) {
if (trim($value) != '') {
$sqlSecondaryFields.= trim($key) . ", ";
$sqlSecondaryValues.= ":" . trim($key) . ", ";
}
}
$sqlSecondaryFields = rtrim($sqlSecondaryFields, ", ");
$sqlSecondaryFields.= ") ";
$sqlSecondaryValues = rtrim($sqlSecondaryValues, ", ");
$sqlSecondaryValues.= ")";
$sqlSecondaryStmt = $sqlSecondaryInsert . $sqlSecondaryFields;
$stmt2 = $connPDO->prepare($sqlSecondaryStmt);
$stmt2->bindValue(':lastDocumentInsertID', $lastDocumentInsertID);
foreach ($intersectArray as $key => $value) {
error_log("attempting to bind " . $key . " to value " . $value);
$stmt2->bindValue(':' . $key, $value, PDO::PARAM_STR);
}
$stmt2->execute();
虽然正确生成了 SQL INSERT 语句,但在尝试执行它时,我在 PHP 错误日志中收到以下内容:
"IMSSP",-29,"Tried to bind parameter number 0. SQL Server supports a maximum of 2100 parameters."
PHP 日志显示了 foreach 循环中 error_log 中的正确键和值,所以我不明白为什么 PDO bindValues 不起作用。
$intersectArray 的示例 print_r 可以在这里看到:
[DocumentNumber] => 123
[ValidFromDate] => 02/09/2015
[ValidExpiryDate] => 26/09/2015
编辑:一些可能有用也可能没用的附加信息:我们使用的是 SQL Server 2008。我不知道这是否相关,我不了解 PDO 驱动程序有何不同对于 SQLSRV 和 MySQL...
【问题讨论】:
-
DocumentID和DocumentNumber一样吗? -
不,DocumentID 是 $lastDocumentInsertID 值。
-
FWIW,
implode()通常比做类似事情的自定义循环要好得多。 -
@Smar,很高兴你喜欢我的回答。也许给一个upvote而不是在cmets中重复它:P
-
@Adelphia:我正在查看评论列表,该工具没有在帖子中显示答案。