PDO,变量SQL查询,bindParam和Loop

时间:2012-05-15 13:10:19

标签: php mysql loops pdo

我最近从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 ?

如果你能给我一个小例子,我将不胜感激。

谢谢;)

1 个答案:

答案 0 :(得分: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);

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