0

I have the following two colums in my database table.

name = "Alex"
skills= "medical,electronics,books,technology"

Now my question is about to search for a word in the above skill field. If a user types something in the search box, my query will search for a exact whole comma separated word in database table (skills field) not a part of word. For example, if a user types medi, the query should return false but if he types medical or books,then the query should return true as medical or books are both present there.

So can anyone tell me how it can be done in PHP. Also forgive me if I made a mistake as my English is not so strong.

Thanks.

user2826169
  • 285
  • 3
  • 7
  • 16
  • possible duplicate: http://stackoverflow.com/questions/4366730/how-to-check-if-a-string-contains-specific-words – Black Sheep Jan 02 '14 at 13:57
  • Please normalize your database, see also: [_Is storing a delimited list in a database column really that bad?_](http://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) – Wrikken Jan 02 '14 at 13:58

4 Answers4

2

You have a list of words, and a word to search for.

in_array would be ideal here.

$has_skill = in_array(strtolower($search),explode(",",strtolower($skills)));

Note that I've converted all strings to lowercase to ease searching.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

In php you can use the stripos function http://php.net/stripos

i.e. :

if (stripos($skills,',books,')!==false || stripos($skills,'books,')===0) echo $name have the skill books;

Or directly under SQL with a like '%,myword,%'

i.e. :

select name from table where skills like '%,books,%' or skills like 'books,%';

Edit. added case where skill is the first

dagfr
  • 2,349
  • 1
  • 19
  • 22
1
$is_in_string = in_array($name,explode(",",$skills));

Note: using explode(",",$skills) every time plenty of users type letter would be time consuming.

Andy
  • 1,035
  • 1
  • 12
  • 28
0
$keywords = preg_split("/[\s,]+/", "medical,electronics,books,technology");
$search='electronics';
$o=in_array($search,$keywords);
if($o==1){
   echo 'yes founded '.$search.'<br/>'; 
}
   else{
echo 'sorry '.$search.'<br/>';       
   }
print_r($keywords);