在foreach循环中绑定数组值时,IMSSP“尝试绑定参数编号0”错误

时间:2015-09-29 13:37:52

标签: php arrays pdo foreach

我有一个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不起作用。

此处可以看到print_r的{​​{1}}示例:

$intersectArray

编辑:一些可能有用或可能没用的其他信息:我们正在使用SQL Server 2008.我不知道这是否相关,我不了解PDO驱动程序有何不同对于SQLSRV和MySQL ......

1 个答案:

答案 0 :(得分:0)

试试这个:

这里是example

function generateInsert($table, $data){
    $sql = "INSERT INTO $table (".implode(", ", $data).") VALUES (:".implode(", :", array_keys($data)).")";
    $exe = array();
    foreach($data as $k=>$v) { 
      $exe[":$k"] = $v;
    }
    return array("sql"=>$sql, "exe"=>$exe);
}

$q = generateInsert("TCMS_Documents", $intersectArray);

$sql = $q['sql'];
$exe = $q['exe'];
$stmt = $connPDO->prepare($sql);
$stmt->execute($exe);

请确保将lastDocumentInsertID列添加到$intersectArray数组中。