Split up keyword query individual parts loop - php

I have Chinese php search queries.
I want to split up any query up into individual characters.
ex: 你好 (ni hao, hello) split into 你 and 好
my query is set like:
$q = $_REQUEST["q"];
the results I want to split is set up like:
$results4 = $db->query( "SELECT CHS, PIN, DEF FROM FOUR
WHERE CHS LIKE '%".$q."%' OR PIN LIKE '%".$q."%'");
while ($row4 = $results4->fetchArray()) {
How can I split up the keyword and look up all the components?

If you want it all in one query you will have to generate the whole query. If you were looking for an exact match you could use something similar to the in_array() function, but with LIKE it doesn't work.
You could however loop through the array of characters and put together the WHERE part programatically.
Like this
$where = array();
foreach ( $qtwo as $word ) {
$where[] = "CHS LIKE '%" . $word . "%'";
}
$where = implode(' OR ', $where);
Use this $where variable in your query

You can use str_split to convert a string in an array of chars
$chars = str_split($q)

Related

SQL Searching Query using LIKE

I have implemented searching using Query having LIKE clause with % wild cards on both side.
I have column having names of countries. If I search with P or PAK it shows result But If I search it with 'I live in Pakistan' it doesn't compare.
The thing I understand is it matches with the sub string.
Is it possible to make its vice versa like I pass the string 'I live in Pakistan' and it matches with characters in fields and gets the result of Pakistan.
Instant help would be appreciated.
you could use the like() function from codeigniter framework.
$this->db->like();
This function enables you to generate LIKE clauses, useful for doing searches.
Note: All values passed to this function are escaped automatically.
Simple key/value method:
$this->db->like('title', 'match');
// Produces: WHERE title LIKE '%match%'
If you use multiple function calls they will be chained together with AND between them:
$this->db->like('title', 'match');
$this->db->like('body', 'match');
// WHERE title LIKE '%match%' AND body LIKE '%match%
If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default).
$this->db->like('title', 'match', 'before');
// Produces: WHERE title LIKE '%match'
$this->db->like('title', 'match', 'after');
// Produces: WHERE title LIKE 'match%'
$this->db->like('title', 'match', 'both');
// Produces: WHERE title LIKE '%match%'
If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.
$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'
See This
I think what you Need is to search and compare for every word in the provided text, i think this will be helpfull.
$temp = array();
$str = array();
$str = explode(' ', $string);
foreach ( $str as $word) {
if (strlen($word) > 2) {
$this->db->or_like('country_name', $word, 'both');
} else {
continue;
}
}
$countries = $this->db->get('countries');
i think in $countries you will have all the needed result.
You could replace the whitespaces with commas, and then use find_in_set. Assuming your string is $str, consider this query:
SELECT *
FROM countries c
WHERE c.name LIKE '%$str%' OR
FIND_IN_SET(c.name, REPLACE($str, ' ', ',')) > 0
Try this
public function searchCountry($value)
{
$value = $value;
$query = $this->db->query("SELECT * FROM table_name WHERE country LIKE '%$value%' ");
$result = $query->result_array();
return $result;
}
This could work (disclaimer: not tested):
public function searchCountry($value)
{
$sql = "SELECT DISTINCT FROM `countries`";
$value = explode(' ', $value);// use all words from query
$first_match = FALSE;
foreach ($value as $k => $v)
{
if (strlen($v) >= 3)// exclude 1 and 2 letter words if want
{
if ( ! $first_match)
{
$sql .= " WHERE `name` LIKE %$v%";
}
else
{
$sql .= " OR `name` LIKE %$v%";
}
}
}
$sql .= " LIMIT 50";
$query = $this->db->query($sql);
$result = $query->result_array();
return $result;
}
but you probably should use #Mureinik solution.
You can use a regular expression trick for this purpose:
where country regexp replace($str, ' ', '|')
This constructs the expression:
where country regexp 'I|live|in|Pakistan'
which the evaluates to true because of the rules for regular expressions.

Splitting a string to put into a CodeIgniter Active Record SQL query

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();
}

How to search in database when the search term is a string that includes spaces?

I have this string "Beautiful sunset" (notice the double space)
When I search in the database:
SELECT * FROM images WHERE title LIKE '%$string%'
and I search for "Beautiful sunset" (notice the single space) it won't return any results.
How can I tackle this?
split the string by space.
now you have two strings something like $str1, $str2
trim this two strings(i.e remove leading and trailing whitespaces)
then rebuild string
$string = $str1+'%'+$str2
Try this
SELECT * FROM images WHERE where MATCH(title) AGAINST ('$string' IN BOOLEAN MODE)
Check this Link also
http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html
You could split your search string into multiple parts using the space and then build a sql like this for every part you have splitted:
SELECT * FROM images WHERE title LIKE '%$part[0]%'
or title LIKE '%$part[1]%'
or title LIKE '%$part[2]%'
or title LIKE '%$part[3]%'
...
Make sure to skip double spaces / empty parts.
One way you can do this is to use string replace to replace spaces with a wildcard character:
$string = str_replace(" ", "%", $string);
$Query = "SELECT * FROM images WHERE title LIKE '%$string%'";
If you don't know what string you're going to get (if it isn't "Beautiful sunset" all the time), you could explode the string and make a query based on that. Like so...
$c = false;
$stringtosearch = "Beautiful sunset";
$query = "SELECT * FROM images WHERE";
foreach(explode(" ", $stringtosearch) as $b)
{
if ($c)
{
$query .= " or";
}
$query .= " title LIKE " . $b;
$c = true;
}
And afterwards you would get the variable $query with your query string.

php tokenisation

I have a string of characters separated by many hashes (#). I need to get the individual words in between the hashes on php. here's what my code looks like:
$sql = "SELECT attribute_type.at_name,attribute_type.at_id FROM attribute_type
WHERE attribute_type.prodType_id = $pt_id
AND attribute_type.at_id NOT IN (SELECT at_id
FROM attribute_type
WHERE attribute_type.at_name = 'Product')";
while($items. strpos("#")>0){
// add the selected AT in every loop to be excluded
// .
// here tokens from $items are stored individually in
// $selectedAT (whose value changes in every loop/cycle)
//
// add to the current sql statement the values $at_id and $searchparam
$sql = $sql . "AND attribute_type.at_id NOT IN
(SELECT at_id FROM attribute_type
WHERE attribute_type.at_name = '$selectedAT')";
}
$dbcon = new DatabaseManager();
$rs = $dbcon->runQuery($sql);
explode creates an array by splitting a string on a given token
$words = explode("#", $items);
Now if you need to take these words you extracted from the string and use them to compare to some column in a SQL query...
$sql = "SELECT ... WHERE column IN ('" . implode("', '", $words) . "')";
You should not need to build a query in a loop as you are doing once you have the words in an array.
Even if you did want to do it that way, you don't want to create a subquery for every word when you could just OR the words together in one subquery.
Try strtok. Example paste:
$string = "This is\tan example\nstring";
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
Do not use split as suggested in another answer (which has now been updated). It uses old POSIX regulat expressions and it's deprecated.
To split a string, use $words = explode('#', $items); which does not use a regular expression but a plain string.
Docref: http://php.net/explode

mysql split search string by space and push into query

The search query is:
"product1 prod2 prod4"
I need to make the mysql
SELECT *
FROM tableprod
WHERE (prod LIKE '%product1%'
AND prod LIKE '%prod2%'
AND prod LIKE '%prod4%')
using the mysql_real_escape_string for the input query...
Simple string manipulation:
$terms = explode(' ', $search);
$bits = array();
foreach ($terms as $term) {
$bits[] = "prod LIKE '%".mysql_real_escape_string($term)."%'";
}
$query = "SELECT * FROM tableprod WHERE (".implode(' AND ', $bits).")";
If you can meet the constraints, you migh be better off just using a FULLTEXT index which would save you the trouble of having to split the string, plus you'd get the bonus of being able to use basic boolean operators for the search (and/or/not)
without a loop(i've always tried to avoid loops):
$str = "product1 prod2 prod4";
$sql = "select * from tableprod where (prod like '%" . str_replace( ' ', '%\' AND prod LIKE \'%', $str ) . '%\')';
if it's possible you will have more than one space inbetween items use preg_replace

Categories