user1257255
user1257255

Reputation: 1171

CodeIgniter - Search results - How to create good query and URI?

I'm working on some script and I would like to create search. My project is based on CodeIgniter and my desire is to have all code content compatibile with it.

So, I have already working on the query for searching but it's not good because it doesn't support more words than one. So if I enter word "test" in my search form (assume that the test word is in database in one of fields) there will be few results, but if I enter words "test test test" (again assume that the test words are in database in one of fields) there will be no any result.

My current query:

$this->db->select('title, content, date, hyperlink')->or_like(array('title' => $query, 'content' => $query))->order_by('id_article', 'desc')->get('news');

The next problem is with URI because if I search for "some article, today is sunny" there is problem with comma and in other cases probably with other disallowed characters too. I have read few other question there, but all that I found is $this->uri->uri_to_assoc(), which I think in my case wouldn't work, because I don't use English in my project.

What's the best solution for these two problems?

Upvotes: 1

Views: 1615

Answers (1)

None
None

Reputation: 5649

To solve the search issue you should probably explode the query into pieces.

$query = 'test test 2 test3';
$parts = explode(' ', $query);

Then loop through the parts and add or_like conditions.

foreach ($parts as $q)
{
    $this->db->or_like(array('title' => $q, 'content' => $q));
}

Now it checks for any of the words.

You may also want to allow quoted values to be treated as one word so that "test 2" would search for the sequence test 2 and not just test and 2. You would need to adjust how you get parts, maybe by a regular expression like:

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $query, $parts);

As for the invalid characters in the URI, pass the string through urlencode on one end then urldecode on the other.

$uri = urlencode('some article, today is sunny');

Upvotes: 1

Related Questions