Search code examples
phpmysqlsearchcell

MYSQL filter by multiple values in same cell?


MYSQL can do the next?

My Terms = a b c

My Query = SELECT * FROM pages WHEREcontentCONTAINS (a AND b AND c)

I need make a query with multiple terms in a page (a searcher). If I've a cell with "1a2b3c" this must be filtered and if other cell have "1a2b4d9i" so the second mustn't be filtered.

Also, if is possible, I want filter by words. Like a "1a2b3c" --> "1 a 2 b 3 c", and won't filter if the text it's joined.

I test this code

$sql = mysql_query("SELECT * FROM pages WHERE "
                      ."(`title` LIKE '%$s%' OR "
                      ."`title` LIKE '%$s' OR "
                      ."`title` LIKE '$s%' OR"
                      ."`content` LIKE '%$s%' OR "
                      ."`content` LIKE '%$s' OR "
                      ."`content` LIKE '$s%') "
                      ."AND `name` != 'inicio' "
                      ."AND `name` != 'contactenos' "
                      ."AND `name` != '404' "
                      ."AND `name` != '403' "
                      ."AND `name` != 'login'");

With one value works great, but with 2 or more values it can't find something.

Also I tried (a,b,c) and a|b|c with AGAINST, REGEX and other but I couldn't make it works.


EDIT 1: If I search "foo bar" and my php code convert it to an array, How can I do to write on MYSQL? I need if I search "foo bar" and my text it's "the foo bar is awesome" and other text is "the foo is worst" only print the first.


Solution

  • You can make your query a lot shorter. You could use something like this

    $sql = mysql_query("SELECT * FROM pages WHERE "
                          ."`title` LIKE '%".$s."%' OR "
                          ."`content` LIKE '%".$s."%' OR "
                          ."AND `name` != 'inicio' "
                          ."AND `name` != 'contactenos' "
                          ."AND `name` != '404' "
                          ."AND `name` != '403' "
                          ."AND `name` != 'login'");
    

    You could use GROUP BY to prevent multiply results:

    $sql = mysql_query("SELECT * FROM pages WHERE "
                          ."`title` LIKE '%".$s."%' OR "
                          ."`content` LIKE '%".$s."%' OR "
                          ."AND `name` != 'inicio' "
                          ."AND `name` != 'contactenos' "
                          ."AND `name` != '404' "
                          ."AND `name` != '403' "
                          ."AND `name` != 'login'") GROUP BY title,content;
    

    For Better Overview :

    $sql = mysql_query("SELECT * FROM pages WHERE "
                      ."`title` LIKE '%".$s."%' OR "
                      ."`content` LIKE '%".$s."%' OR "
                      ."AND `name` NOT IN('inicio','contactenos','404','403','login') GROUP BY title,content;
    

    But please sanitize your variables before using in the query ;)