I'm trying to grab rows from sql using LIKE, where the key matc开发者_JAVA技巧hes key array in the column.
$key = '%PDF%';
$q = mysql_query("SELECT * FROM `ads` WHERE key LIKE '$key' ORDER BY RAND() LIMIT 2");
This works fine and show the results but when i change my key to PDF FILES. i.e.:
$key = '%PDF FILES%';
It doesn't show the results as in the db there is an array of keys, please look at my db column:
Here's My sql Key column:
PDF, pdf, PDF SEARCH, pdf search, PDF ENGINE, pdf
So whats the solution? how to get results if the key is pdf files?
I think it can be by splitting the key and then matches the keywords. right?
this can be done by explode();
but how? and how to match with sql?
When the key is '%PDF FILES%'
, you are actually searching for the string "PDF FILES" and not some combination of the words PDF and FILES.
To achieve what you want, try constructing a query like:
$key = '%PDF%';
$key2 = '%FILES%';
$q = mysql_query("SELECT * FROM `ads` WHERE (key LIKE '$key' OR key LIKE '$key2') ORDER BY RAND() LIMIT 2");
You can use various techniques with arrays and explode to construct a dynamic query with a variable number of keywords.
Try this,
$keyvalues=split(" ",$search_text);//Breaking the string to array of words
// Append the query by the keywords
while(list($key,$val)=each($keyvalues)){
if($val<>" " and strlen($val) > 0)
{$sql .= " name like '%$val%' or ";}
}// end of while
The trailing OR can be removed by
$sql=substr($sql,0,(strlen($sql)-3));
This is because LIKE works with only one string. You have to use more LIKE statements with OR in case you want to use wildcards.
On the other hand you can use IN which accepts comma seperated quoted strings, but it doesn't accept wild cards.
You can not enter multiple keywords for Like in One single statement.
You can try for this it will help you.
WHERE key LIKE '%PDF%' OR '%pdf%' OR '%PDF SEARCH%'
and so on.....
精彩评论