尝试让PDO执行时出错

时间:2018-05-30 21:21:09

标签: php sql pdo binding execute

这有效,我将print_r上回显的代码粘贴到execute语句中,一切都很好。

$search_items = array();
for ($x = 0; $x < $search_parts_count; $x++) {
     $search_items[] = "':search$x' => '%$search_parts[$x]%'";
}
print_r(implode(",", $search_items));

$stmt->execute(array(':search0' => '%cure%',':search1' => '%cancer%',':search2' => '%help%',':search3' => '%ongoing%'));

但是当我这样做时:

$stmt->execute($search_items);

我明白了:

  

带有消息'SQLSTATE [HY093]的未捕获异常'PDOException':参数号无效:绑定变量数与令牌数不匹配'

不知道我做错了什么。任何帮助将不胜感激!

以下是声明:

$sql_string = 'SELECT area, file_name, title FROM meta_details WHERE' . $search_guts;
    $stmt = $conn->prepare($sql_string);

它的构建方式如下:

$search_guts = '(';

    for ($x = 0; $x < $search_parts_count; $x++) {
        $search_guts .= 'title LIKE :search' . $x;
         if ($search_parts_count - 1 != $x){$search_guts .= ' OR ';}
        };

    $search_guts .= ') OR (';   

    for ($x = 0; $x < $search_parts_count; $x++) {
        $search_guts .= 'description LIKE :search' . $x;
         if ($search_parts_count - 1 != $x){$search_guts .= ' OR ';}
        };          
        $search_guts .= ')';

谢谢!

1 个答案:

答案 0 :(得分:0)

构建$search_items ...

$search_items[] = "':search$x' => '%$search_parts[$x]%'";

您正在创建值为"':search$x' => '%$search_parts[$x]%'"的项目,而不是:search$x的条目。你应该像......一样......

$search_items[":search$x"] = "%{$search_parts[$x]}%";