CodeIgniter Forums

Full Version: Search query , multiple words ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]nebi[/eluser]
How can I fix so I can use multiple word in a search query ?

My sql query look like this :

Code:
$this->db->select('*')->from('quotes')->like('quote', $search , 'both')->where('approve',1)->limit($num, $offset);



I have no problem with single word , example $search = "and" return right results but if I change $search to "and you" it will return zero results. Is there any easy solution to this problem or I am forced to use a search engine of any kind ?

El Forum

[eluser]Madmartigan1[/eluser]
What does the sql statement say when you run the profiler?

Code:
$this->output->enable_profiler(TRUE);

El Forum

[eluser]nebi[/eluser]
This is the output :

Code:
POST DATA  
$_POST['search']       om och

DATABASE:  lcitat   QUERIES: 2  
0.0060      SELECT COUNT(*) AS `numrows`
FROM (`quotes`)
WHERE `approve` = 1
AND  `quote`  LIKE '%om och%'


0.0060      SELECT *
FROM (`quotes`)
WHERE `approve` = 1
AND  `quote`  LIKE '%om och%'
LIMIT 20

El Forum

[eluser]Madmartigan1[/eluser]
As long as '%om och%' is in your table (where approve=1) I have no idea. The query is right. Just wanted you to know I wasn't ignoring you, as I saw no further replies.

El Forum

[eluser]nebi[/eluser]
Well if the two word is after each other in the table then it's no problem , but I want more like this '%om%och%'

Edit : I realise that i must do a array of $search , but how do I make that every word a new value in a array ?

El Forum

[eluser]Madmartigan1[/eluser]
Would it help to do this? It will work.

Code:
//turns 'my search' into '%my%search%'
$search=preg_replace('/\s\s++/','%',$search);//replace spaces with %
$search='%'.$search.'%';

$this->db->select('*')->from('quotes')->like('quote', $search , 'both')->where('approve',1)->limit($num, $offset);

El Forum

[eluser]nebi[/eluser]
Thanks , didnt work but you did point me in right direction Smile

This solved my problem

$search=str_replace(' ','%',$search);//replace spaces with %

El Forum

[eluser]Madmartigan1[/eluser]
Sorry, my typo, should've been.

Code:
$search=preg_replace('/\s\s+/','%',$search);

If you use preg_replace instead, you will remove multiple spaces just in case.
No need for '%my%%%search%' but it doesnt matter, same thing
str_replace is faster though

Glad you got it working!

El Forum

[eluser]Nelson Mendes[/eluser]
hmmm... I'm a bit late for this thread, but if you're searching for multiple words, then this example will search for those words in that specific ORDER. I'm not sure if that's what you are looking for, but that's not usually the case.