动态数量的bindParam

时间:2019-01-19 23:55:22

标签: php mysql pdo prepared-statement

因此,我试图在foreach中进行数量不确定的bindParam调用,但是由于某种原因,它失败了。我知道$ sql变量工作正常,但是我很确定在bindParam上它失败了。有什么理由吗?

$sql = "INSERT INTO " . $row1["rand"] . " (" . $areas . ") VALUES (" . $vals . ")";
echo $sql;
$entry2 = $conn->prepare("'".$sql."'");
//echo "swag";
foreach($splitHeader as $element){
    if(strlen($element)>0) {
        $thisVal = "':" . $element . "'";
        $entry2->bindParam($thisVal,$_POST[$element]);
    }
}
$entry2->execute();

1 个答案:

答案 0 :(得分:0)

您在查询中定义的参数数量必须与您绑定的参数数量匹配。

您需要循环两次以遍历数据:一次是动态构造sql语句(然后您可以prepare),然后是第二次绑定参数,最后才调用execute

这里是您的代码的改编版,它演示了原理:

$cols = "";
$vals = "";
foreach( $splitHeader as $element ) {
    if( strlen($element) > 0 ) {
        if ( strlen($cols) > 0 ) {
            $cols .= ", ";
            $vals .= ", ";
        }
        $cols .= $element;
        $vals .= "?";
    }
}

$sql = "INSERT INTO " . $row1["rand"] . " (". $cols . ") VALUES(". $vals . ")";
echo $sql;
$sth = $conn->prepare($sql);

$i = 1;
foreach($splitHeader as $element){
    if( strlen($element) > 0 ) {
        $sth->bindParam( $i, $_POST[$element] );
        $i++;
    }
}

$sth->execute();