简体   繁体   English

pdo预处理语句不起作用,但普通的查询呢。 我错过了什么?

[英]pdo prepared statements do not work, but an ordinary query does. What am I missing?

For some reason I cannot get this to work: 由于某种原因,我不能让这个工作:

/**
 *  $_COOKIE['MyShoppingList'] is a serialized array with intergers. 
 */
if($_COOKIE['MyShoppingList']){
    foreach(unserialize($_COOKIE['MyShoppingList']) as $recipe){
        $recipes_ids .= $recipe.',';
    }

    $sql_WHERE_NOT_IN = 'WHERE r.id NOT IN (:ids)';
}


$qry_recipes = $dbh->prepare('
    SELECT r.id drink_id, r.name drink_name
    FROM recipes r
    '.$sql_WHERE_NOT_IN.'
');
if($_COOKIE['MyShoppingList']){
    $qry_recipes->execute(array(':ids'=>rtrim($recipes_ids,',')));  //  I've verified that this is in fact a string with all the intergers sepparated with a comma.
} else {
    $qry_recipes->execute();
}

This does work like a charm: 这确实像魅力一样:

if($_COOKIE['MyShoppingList']){
    /*  the $recipes_id is the same as before  */
    $sql_WHERE_NOT_IN = 'WHERE r.id NOT IN ('.rtrim($recipes_ids,',').')';
}


$qry_recipes = $dbh->query('
    SELECT r.id drink_id, r.name drink_name
    FROM recipes r
    '.$sql_WHERE_NOT_IN.'
');

The only difference is that the former is using prepared statements, and the latter is a pure query. 唯一的区别是前者使用预处理语句,后者是纯查询。

What happens is that it looks like the former, prepared, is not detecting the $recipes_ids -string.. 发生的事情是看起来前者准备好了,没有检测到$recipes_ids -string。

Is there something about the $recipes_ids I'm overlooking? 有什么关于我正在忽略的$recipes_ids吗?

rtrim(...) string (13) "12,1,2,3,9,10"  //  it's like this in both scenarios

I've tried bindParam() as well, but that resulted in this error message: 我也试过bindParam() ,但是这导致了这个错误信息:

"Strict Standards: Only variables should be passed by reference"

I'm not sure what that means, but it might be telling me what I should be doing.. 我不确定这意味着什么,但它可能告诉我应该做什么。
So please let me know.. 所以请让我知道..

Also; 也; I've tried putting rtrim($recipes_ids,',') into a variable before sending it to the prepared query - but with no luck.. 我已经尝试将rtrim($recipes_ids,',')放入变量中,然后将其发送到准备好的查询中 - 但没有运气..

You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement. 您不能将多个值绑定到单个命名参数,例如,SQL语句的IN()子句。

Try this way: 试试这种方式:

/**
 *  $_COOKIE['MyShoppingList'] is a serialized array with intergers. 
 */
$recipes_ids = array();
if($_COOKIE['MyShoppingList']){
    foreach(unserialize($_COOKIE['MyShoppingList']) as $recipe){
        $recipes_ids[] = $recipe;
    }

    $sql_WHERE_NOT_IN = 'WHERE r.id NOT IN (' . str_repeat('?, ', count($recipe_ids) - 1) . '?)';
}


$qry_recipes = $dbh->prepare('
    SELECT r.id drink_id, r.name drink_name
    FROM recipes r
    '.$sql_WHERE_NOT_IN.'
 ');
if($_COOKIE['MyShoppingList']){
    $qry_recipes->execute($recipe_ids);
} else {
    $qry_recipes->execute();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM