1

我最近从 mysql_ 函数转移到 PDO,有些东西我无法适应我的情况。

问题是搜索查询,实际上我正在这样做:

$resultat = $DB->prepare('SELECT * FROM `posts` WHERE `title` LIKE :searchterm OR `tags` LIKE :searchterm LIMIT '.$debut.', '.NB_ART);
$resultat->bindParam(':searchterm',$searchterm);
$resultat->execute();

知道查询的大小可能会根据用户搜索而改变,我该怎么做这样的事情:

$tab = explode(' ',$searchterm);
$query = 'SELECT * FROM posts WHERE ';

foreach($tab as $value){
    if( strlen($value)>2 ){
        $query .= ' (`title` LIKE "%'.$value.'%" OR `tags` LIKE "%'.$value.'%") AND';
    }
}
$query = substr($query,0,-3);
$query .= 'ORDER BY `date` DESC';

// And how can i do the bindParam() here ?

如果您能从一个小例子开始,我将不胜感激。

谢谢 ;)

4

1 回答 1

1
$data = array();
$arr_query = array();

$tab = explode(' ',$searchterm);
$query = 'SELECT * FROM posts WHERE ';

foreach($tab as $value){
    if( strlen($value)>2 ){
        // sry for that, but i think implode() better
        $arr_query[] = '(`title` LIKE ? OR `tags` LIKE ?)';

        $data[] = '%'. $value .'%';
        $data[] = '%'. $value .'%';
    }
}
$query .= implode(' AND', $arr_query);
$query .= ' ORDER BY `date` DESC';

$res = $pdo->prepare($query);
$res->execute($data);

第一个示例中的限制也必须受到保护。

于 2012-05-15T13:45:29.307 回答