Search code examples
phpmysqlmysqlisql-like

I need to search field value in LIKE pattern of sql statement


My table looks like this

Id  | name   
---------------
1   |  clinker
2   |  gypsum

Now I need to prepare a search based on the 'name' field. here is the select statement

select * from table where name like '%$keyword%'

Now, suppose the keyword is 'clinker 1', and I want first row of my table as result set. How can I accomplish that?


Solution

  • Not quite sure about MySQL, but LIKE should work with any character expression on either or both sides. That includes both columns and literals. Hence, the LIKE can be used the other way around to find the inverse matches:

    SELECT *
    FROM table
    WHERE name LIKE '%$keyword%'
    OR '$keyword' LIKE CONCAT('%', name, '%')