【问题标题】:Binding params for PDO statement inside a loop循环内 PDO 语句的绑定参数
【发布时间】:2011-05-09 15:21:20
【问题描述】:

我正在尝试为循环内的 SQL 查询绑定参数:

$db = new PDO('mysql:dbname=test;host=localhost', 'test', '');  
$stmt = $db->prepare('INSERT INTO entries VALUES (NULL, ?, ?, ?, NULL)');

$title = 'some titile';
$post = 'some text';
$date = '2010-whatever';  

$reindex = array(1 => $title, $post, $date); // indexed with 1 for bindParam

foreach ($reindex as $key => $value) {  
    $stmt->bindParam($key, $value);  
    echo "$key</br>$value</br>";  //will output: 1</br>some titile</br>2</br>some text</br>3</br>2010-whatever</br>
}

上面的代码在2010-whatever的所有3个字段中插入数据库。

这个很好用:

$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);

那么,我的问题是为什么 foreach 循环中的代码会失败并在字段中插入错误的数据?

【问题讨论】:

    标签: php foreach pdo prepared-statement


    【解决方案1】:

    问题是bindParam 需要引用。它将变量绑定到语句,而不是值。由于foreach 循环中的变量在每次迭代结束时都未设置,因此您不能使用问题中的代码。

    您可以使用foreach 中的引用执行以下操作:

    foreach ($reindex as $key => &$value) {  //pass $value as a reference to the array item
        $stmt->bindParam($key, $value);  // bind the variable to the statement
    }
    

    或者你可以这样做,使用bindValue:

    foreach ($reindex as $key => $value) {
        $stmt->bindValue($key, $value);  // bind the value to the statement
    }
    

    【讨论】:

    • 您好 Ionesomeday - 我遇到了类似的问题。你能帮我解决这个问题吗? stackoverflow.com/questions/34285341/…
    • 问题是——哪一个更好? bindValue 或 bindParam。
    • @IdanMagled 这里我认为bindValue 更直观。 bindParam 在某些情况下具有优势。
    • &amp;&amp;$value 中做了什么?
    • @Taurus 它使$value 成为对数组元素的引用,而不是复制它的值。
    猜你喜欢
    • 2020-09-05
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2012-01-27
    • 2011-03-23
    相关资源
    最近更新 更多