Create Multi Keyword Search On PHP

I just create multi keyword search using php, so search a single column on db. This is working example.

// example three word: batman superman robin
//no we explode that string by space
$pecah = explode(" ",$q);
//we need to continous that string outside the loop
$kondisi ='';
//then define column we need to search those keywords
$kolom = 'judul'; 
//now 
 foreach($pecah as $data=>$key)
 {
     $kondisi .= '\'%' .$key . '%\' OR ' .$table . ' LIKE ';
 }
//then, remove 15 last unwante string
$bersihin = substr($kondisi,0,-15);

//then $bersinin is ready to stay on sql query
$array = $pdo->query("SELECT * FROM YOUR_TABLE  WHERE $kolom LIKE $bersihin")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('data' =>$array));

Above code will produce $bersihin as:
‘%batman%’ OR judul LIKE ‘%robin%’ OR judul LIKE ‘%sungo%’ OR judul LIKE ‘%kong%’

AND final query will be:
SELECT FROM YOUR_TABLE WHERE judul LIKE ‘%batman%’ OR judul LIKE ‘%robin%’ OR judul LIKE ‘%sungo%’ OR judul LIKE ‘%kong%’

Demo, get this movie API

Share to

Do You Know!