0

当我尝试运行以下函数时,我收到错误“SQLSTATE [HY093]:无效的参数号:绑定变量的数量与令牌的数量不匹配”:

    public function find_products($string = '', $fields = array(), $sort_by = '', $sort_dir = 'ASC') {

    $fields = empty($fields) ? '*' : ('' . implode(',', $fields) . '?');
    $bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%');
    $and_where_checks = array('series','material');
    $AND = '';

    // Loop through the POST variables to see what is safe to play with
    $allowed = array();
    foreach ($and_where_checks as $awc)
        if ( ! empty($_POST[$awc]))
            $allowed = $awc;

    if ( ! empty($allowed)) {
        $tmp = array();
        foreach ($allowed as $v)
            $tmp = '' . $v . ' IN (' . str_pad('', count($v) * 2 - 1, '?,') . ')';

        $AND = 'AND (' . implode(' AND ', $tmp) . ') ';

        foreach ($allowed as $k)
            foreach ($_POST[$k] as $v)
                $bindings = $v;
    }

    $query = 
        "SELECT " . $fields . " FROM " . $this->product_table . " " . 
        "WHERE (" . $this->primary_key . " LIKE ? " .
        $AND . 
        "ORDER BY " . $sort_by . " " . $sort_dir;

    $sth = $this->$dbh->prepare($query);

    $sth->execute($bindings);

    return $sth->fetchAll(PDO::FETCH_ASSOC);
}

$POST[$awc] 变量由此页面http://ladd-dev.bitstormweb.com/products/interactive-product-finder/上的复选框填充。当我选择每个复选框组中的一个(例如 1 个系列和 1 个材料)时,结果很好,但是当我在同一组中选择多个框时,我得到了 PDOException。

有谁知道为什么?我仍在学习此代码,因此将不胜感激!

4

1 回答 1

0

在您的查询中,您只有一个要绑定的变量(?):

$query = 
    "SELECT " . $fields . " FROM " . $this->product_table . " " . 
    "WHERE (" . $this->primary_key . " LIKE ? " .
    $AND . 
    "ORDER BY " . $sort_by . " " . $sort_dir;

在这里,您必须绑定 0 或绑定超过 1。检查 $bindings 中有多少值。

$sth = $this->$dbh->prepare($query);
$sth->execute($bindings);

您可以通过使用检查 $bindings 中有多少值print_r($bindings);

更新:在不知道您的输入是什么的情况下,您的代码似乎使用了两次 $bindings。它在顶部设置了 3 个相同的值:$bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%');然后在底部有一个 foreach,你根本不使用数组:

foreach ($_POST[$k] as $v)
            $bindings = $v;
于 2014-04-21T17:02:06.127 回答