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 つのマテリアル) の 1 つを選択すると、結果は問題ありませんが、同じグループで複数のボックスを選択すると、PDOException が発生します。

誰かが理由を知っていますか?私はまだこのコードを学んでいるので、助けていただければ幸いです!

4

1 に答える 1

0

クエリでは、バインドする変数は 1 つだけです (?)。

$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 を 2 回使用しているようです。それは同じものである 3 つの値で上部に設定されてい$bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%');ます。下部には、配列をまったく使用していない foreach があります。

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