Search code examples
phpmysqlfull-text-searchrlike

Advanced MySQL search query - using RLIKE


Im working on a MySQL search query for a product search module in Joomla/Virtuemart. I am actually trying to modify an existing MySQL query from using MATCH / AGAINST to using RLIKE, but my modified query gives errors..

Here is the original query with MATCH / AGAINST which has no errors:

$searchstring = " +search* +string* +test*";
$query ="SELECT p.virtuemart_product_id, l.product_name from #__virtuemart_products AS p, #__virtuemart_products_".VMLANG." AS l WHERE MATCH(product_name,customtitle) AGAINST ('".$searchstring."' IN BOOLEAN MODE) AND p.published = '1' AND p.virtuemart_product_id = l.virtuemart_product_id  LIMIT 0,".$prods." union (select p.virtuemart_product_id, l.product_name from #__virtuemart_products AS p, #__virtuemart_products_".VMLANG." as l where  MATCH(product_sku) AGAINST ('".$searchstring."' IN BOOLEAN MODE) and p.published = '1'  and p.virtuemart_product_id = l.virtuemart_product_id LIMIT 0,".$prods.")";

Here is my altered query using RLIKE:

$searchstring = "search|string|test";
$query ="SELECT p.virtuemart_product_id, l.product_name from #__virtuemart_products AS p, #__virtuemart_products_".VMLANG." AS l WHERE product_name,customtitle RLIKE '".$searchstring."' AND p.published = '1' AND p.virtuemart_product_id = l.virtuemart_product_id LIMIT 0,".$prods." union (select p.virtuemart_product_id, l.product_name from #__virtuemart_products AS p, #__virtuemart_products_".VMLANG." as l where product_sku RLIKE '".$searchstring."' and p.published = '1'  and p.virtuemart_product_id = l.virtuemart_product_id LIMIT 0,".$prods.")";

I am out of ideas as to why the RLIKE search query does not work. I hope someone can point out what I´m doing wrong here..


Solution

  • You have this weird expression in your query:

    WHERE product_name, customtitle RLIKE '".$searchstring."'
    

    Try combining them using concat() first:

    (SELECT p.virtuemart_product_id, l.product_name
     from #__virtuemart_products p join
          #__virtuemart_products_".VMLANG." l
          on p.virtuemart_product_id = l.virtuemart_product_id
     WHERE concat(product_name, customtitle) RLIKE '".$searchstring."' AND
           p.published = '1'
     LIMIT 0,".$prods."
    )
    union
    (select p.virtuemart_product_id, l.product_name
     from #__virtuemart_products p join
          #__virtuemart_products_".VMLANG." l
          on p.virtuemart_product_id = l.virtuemart_product_id
     where product_sku RLIKE '".$searchstring."' and
           p.published = '1'
     LIMIT 0,".$prods.
    )
    

    You could also compare each one separately:

     WHERE (product_name RLIKE '".$searchstring."' OR
            customtitle RLIKE '".$searchstring."' 
           ) AND . . .
    

    Note that I also fixed the join syntax to use explicit joins.