Piokaz
Piokaz

Reputation: 374

PDO, Variable SQL Query, bindParam and Loop

I recently moved from mysql_ functions to PDO, and there is something i can't adapt to my situation.

The problem is the search query, actually i'm doing like that :

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

Knowing that the size of the query may change depending on user search, how can i do something like that :

$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 ?

I'll appreciate if you can show me a small example to start with.

Thanks ;)

Upvotes: 1

Views: 446

Answers (1)

ShaaD
ShaaD

Reputation: 626

$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);

limits in the first example must be protected too.

Upvotes: 1

Related Questions