【问题标题】:PHP failing to build a PDO query dynamically.PHP 无法动态构建 PDO 查询。
【发布时间】:2012-06-24 18:43:39
【问题描述】:

所以我正在尝试使用 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]:参数号无效:参数未定义'

帮助?

【问题讨论】:

    标签: php pdo


    【解决方案1】:

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

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

    【讨论】:

    • 确实如此。你能解释一下为什么有时它可以在没有冒号的情况下工作吗?例如,这很好用。 $st = $dbh->prepare('SELECT * FROM hotels WHERE id = :id'); $st->execute(array('id' => 1)); var_dump($st->fetch());
    猜你喜欢
    • 1970-01-01
    • 2012-01-08
    • 2010-10-09
    • 2015-03-28
    • 1970-01-01
    • 2012-11-23
    • 2019-04-08
    • 2012-12-21
    • 2018-12-21
    相关资源
    最近更新 更多