I am trying to do a search query to see if a textarea contains some keywords. I'm having a bit of trouble though plugging my textarea's values into the query.
This is my query:
$match = $this->input->post('wStory');
$this->db->where("`terms` LIKE '%$match%'");
$query = $this->db->get('filter_tbl');
return $query->num_rows();
The $match
is my text field and what I have been trying to do is split up the words inside and then run through each individual word. I have tried using PHPs' explode()
function which sort of works, but in this case it doesn't work because it turns the string into an array.
Is there any way I can split up the strings in my textarea to just words and run through the words in the like statement, Or is there just something I'm missing?
The query you're currently running is doing a check for a specific phrase, rather than checking for any of the specified words.
You need to do the following:
$match = $this->input->post('wStory');
// break search phrase into keywords
$keywords = explode(' ', $match);
// Build query
foreach ($keywords as $keyword)
{
$keyword = trim($keyword);
$this->db->or_where("`terms` LIKE '%$keyword%'");
}
$query = $this->db->get('filter_tbl');
return $query->num_rows();
The explode(' ', $match)
does not take into account any punctuation that might separate words.
Isn't there a $this->db->like("terms", $match);
method?
See http://ellislab.com/codeigniter/user-guide/database/active_record.html#like
I think fulltext search is the way to go. The url Rob W posted also gives this:
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
which in you care would be something like
$this->db->where('MATCH (terms) AGAINST ("$match")', NULL, FALSE);
Edit: After reading some further, this might be better (or atleast better readable):
$this->db->where('MATCH (terms) AGAINST ("$match")');
Try this:
$match = $this->input->post('wStory');
//Getting words from textarea and put them into array
$wordsArray = explode(' ',$match);
if (!empty($wordsArray)) {
//use where_in() instead of where()
$this->db->where_in("`terms`", $wordsArray);
$query = $this->db->get('filter_tbl');
return $query->num_rows();
}