PDO双喜与Params

时间:2015-02-03 08:40:00

标签: mysql pdo parameters sql-like

我正在使用PDO执行查询,该查询不通过PHP检索任何结果,但可以在phpMyAdmin中运行。 我确定连接设置,因为它不是我的脚本的第一个查询,其他的工作正常。 这里是PHP代码:

        $retour = array();
        $filters = array();
        $filters['media_type'] = 'mytype';
        $filters['libelle'] = 'sometext';
        $start = 0;
        $count = 9;

        $sql = "SELECT * FROM ".DB_PROD_PREFIX.$this->table." t ";
        $sql .= " LEFT JOIN ".DB_PROD_PREFIX.$this->table."_lang l ON t.id = l.id AND l.langue = :langue";
        $sql .= " WHERE 1";
        if (count($filter)>0){
            foreach($filter as $field => $value){
                $sql .= " AND ".$field." LIKE :".$field;
            }
        }
        $sql .= ($order!='' ? " ORDER BY ".$order : '');
        $sql .= ($count != '' ? " LIMIT ".($start != ''?':start':'0').", :count" : '');

        $stmt = $db->prepare($sql);
        if($start != '') $stmt->bindParam('start', $start, PDO::PARAM_INT);
        if($count != '') $stmt->bindParam('count', $count, PDO::PARAM_INT);
        if ($langue != '') $stmt->bindParam('langue', $langue);

        if (count($filter)>0){
            foreach($filter as $field => $value) {
                $f = '%'.$value.'%';
                $stmt->bindParam($field, $f, PDO::PARAM_STR);
            }
        }

        echo $stmt->queryString.print_r($filter, true);

        if (!$stmt->execute()) echo $stmt->errorInfo();
        $res = $stmt->fetchAll();
        foreach($res as $id => $row){
            $retour[]=$row;
        }
        return $retour;

如果我取消设置$ filter数组的2个键之一,查询工作正常。 这是SQL生成的:

SELECT * FROM table1 t  
LEFT JOIN table1_lang l ON t.id = l.id AND l.langue = :langue 

WHERE 1 
AND media_type LIKE :media_type 
AND libelle LIKE :libelle 

ORDER BY position LIMIT :start, :count

感谢您的帮助!

Pierre M。

1 个答案:

答案 0 :(得分:0)

效果不好但是感谢小费! 以下是管理LIKE参数的一段代码:

$media_type = '%'.$filter['media_type'].'%';
$stmt->bindParam('media_type', $media_type, PDO::PARAM_STR);
$libelle = '%'.$filter['libelle'].'%';
$stmt->bindParam('libelle', $libelle, PDO::PARAM_STR);

为什么在阵列上对foreach做同样的事情不起作用?

if (count($filter)>0){
    foreach($filter as $field => $value) {
        $value = "%$value%";
        $stmt->bindParam($field, $value, PDO::PARAM_STR);
    }
}