Search code examples
mysqlsearchmatch-against

Trick to use variable in match against mysql


Please first read my question,and then you will find out it is not a duplicate of other question.

I'm using sphinx search for 98% of search,but need to use match against for just one query.

As we know from mysql documentation that AGAINST only takes string.The search string must be a literal string, not a variable or a column name.

But I have found this link http://bugs.mysql.com/bug.php?id=66573 ,which says it is possible.But I'm not sure how to use that in my case.

Here is my code

    $sqli="SELECT busi_title,category FROM `user`.`user_det`";
    $queryi=mysqli_query($connecti,$sqli);
        if(mysqli_num_rows($queryi)>0){
            while($rowi=mysqli_fetch_assoc($queryi)){
              $busi_title=$rowi['busi_title'];
              $category=$rowi['category'];
            }

        }else{
            echo "OH NO";
         }

$sqlj="SELECT * FROM `user`.`user_det` WHERE MATCH(student) AGAINST('$busi_title','$category')";
$queryj=mysqli_query($connecti,$sqlj);
     if(mysqli_num_rows($queryj)>0){
        ..............................
        ..............................
     }else{  
        foreach ( $res["matches"] as $doc => $docinfo ) {
         ................................
          ...............................
         }
      }

MATCH() AGAINST() is giving error,as it supposed to be.How to use that trick of that link in this case.I don't know the use of @word:= of that link.

Thanks in advance.


Solution

  • That link doesn't show a trick to get around a limitation of MySQL. It's a bug report demonstrating an incorrect statement in the MySQL documentation. The statement in the documentation has now been corrected.

    The reason you're getting an error is because you're sending two parameters to AGAINST and it only accepts one. You can use a MySQL variable in AGAINST which is what the bug report is about, but this has nothing to do with the PHP variable that you're using.

    EDIT

    Upon reading your response, I rather suspect that you have your syntax backwards.

    SELECT * FROM `user`.`user_dets` WHERE MATCH(busi_title, category) AGAINST('student')
    

    But note this from the documentation:

    The MATCH() column list must match exactly the column list in some FULLTEXT index definition for the table, unless this MATCH() is IN BOOLEAN MODE. Boolean-mode searches can be done on nonindexed columns, although they are likely to be slow.

    If you don't have a Fulltext index, you'll actually want this:

    SELECT * FROM `user`.`user_dets` WHERE `busi_title` LIKE '%student%' OR `category` LIKE '%student%'