Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP无法动态构建PDO查询。_Php_Pdo - Fatal编程技术网

PHP无法动态构建PDO查询。

PHP无法动态构建PDO查询。,php,pdo,Php,Pdo,因此,我尝试使用PDO(一种动态的mysql查询)来构建和准备。这是我的代码和调试信息 $allowed_filters = array('hotels.star_rating', 'countries.id'); $where = 'WHERE 1 '; if (!empty($data['filters'])){ $where = 'WHERE'; foreach ($data['filters'] as $field => $value){ if (

因此,我尝试使用PDO(一种动态的mysql查询)来构建和准备。这是我的代码和调试信息

$allowed_filters = array('hotels.star_rating', 'countries.id');

$where = 'WHERE 1 ';
if (!empty($data['filters'])){
    $where = 'WHERE';
    foreach ($data['filters'] as $field => $value){
        if (in_array($field, $allowed_filters)){
            $where .= " $field = :$field &&";
        }
        else unset($data['filters'][$field]);
    }

    $where = rtrim($where, '&&');
    $where = ($where == 'WHERE')? 'WHERE 1 ' : $where;
}

$st = $this->db->prepare("
    SELECT 
        hotels.code,
        hotels.name as name,
        hotels.star_rating,
        hotels.description,
        hotels.cover_image,
        countries.name as country,
        cities.name as city 
    FROM  
        hotels JOIN cities ON cities.id = hotels.city_id
        join countries on countries.id = cities.country_id
    $where
");

$st->execute($data['filters']);
var_dump($st->fetch());
就在$st->execute$data['filters']行之前,我转储了$st和$data['filters']。数值如下所示

价值$st

PDOStatement Object
(
    [queryString] => 
        SELECT 
            hotels.code,
            hotels.name as name,
            hotels.star_rating,
            hotels.description,
            hotels.cover_image,
            countries.name as country,
            cities.name as city 
        FROM  
            hotels JOIN cities ON cities.id = hotels.city_id
            join countries on countries.id = cities.country_id
        WHERE 
            hotels.star_rating = :hotels.star_rating && 
            countries.id = :countries.id 
)
$data['filters'的值

Array
(
    [hotels.star_rating] => 4 stars
    [countries.id] => 5
)
PDO引发异常并失败,出现以下错误

SQLSTATE[HY093]:参数编号无效:未定义参数'

帮助?

您忘记了$data['filters'键中的冒号。应该是:

Array
(
    [:hotels.star_rating] => 4 stars
    [:countries.id] => 5
)

没错。你能解释一下为什么有时候它不用冒号吗?例如,这很好$st=$dbh->准备“从id=:id'的酒店选择*”$st->Executarray'id'=>1;var_dump$st->fetch;