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 (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 的值(value)

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]: Invalid parameter number: parameter was not defined'

帮忙吗?

最佳答案

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

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

关于PHP 无法动态构建 PDO 查询。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11180224/

相关文章:

php - X-Frame-Options : does not permit cross-origin framing 拒绝加载

php - 如何使用 github action 部署 Laravel 应用程序

php - MySQLi 附加更多/更深的结果

php - 如何在 PHP 中将 PDF 1.5 版转换为 1.4 版

php - 在类中使用 $this 从空值创建默认对象

PHP使用mysql在变量中发布变量

php - 在PHP中上传图像将文件路径保存到数据库

php - 使用新值更新联结表

php - 从文件导入sql语句时的编码问题

php - 在 'Notifications' 表中插入多行会减慢查询速度吗?