Mysql separates the search string with a space and inserts a query

Search query:

"product1 prod2 prod4"

I need to do mysql

SELECT * 
  FROM tableprod 
  WHERE (prod LIKE '%product1%' 
         AND prod LIKE '%prod2%' 
         AND prod LIKE '%prod4%')

using mysql_real_escape_string for input request ...

+3
source share
3 answers

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).")";
+7
source

If you cope with the restrictions, it would be better for you to use the FULLTEXT index , which saves you from having to split the string, plus you get a bonus to be able to use basic logical operators for searching (and / or / not)

+1
source

( ):

$str = "product1 prod2 prod4";
$sql = "select * from tableprod where (prod like '%" . str_replace( ' ', '%\' AND prod LIKE \'%', $str ) . '%\')';

, , preg_replace

+1

Source: https://habr.com/ru/post/1768906/


All Articles