N.N.Ontika N.N.Ontika - 6 months ago 11
PHP Question

MySQL query does not working for random words matching in a column

I am facing some problems in MySQL query in PHP.

I have the below Bengali words in a column named 'keywords' and they are assigned to 'গৌরিপ্রসন্ন মজুমদার' value of another column named 'name' in a table named 'lyricist'


সয়না,রয়না,কেমন,তাকে,আমার,তুমি,কৃষ্ণ,রাধে,দিতে,চাই,আরো,কাছে,তোমার,আমার,তুমি,থাকো,কাছে,ডাকো,আমি,পড়েছে


When I'm searching for some consecutive words like 'তোমার,আমার,তুমি' I get the correct answer 'গৌরিপ্রসন্ন মজুমদার' But when i'm searching for random words like 'তোমার,তুমি' it's not giving any answer.

$query = "SELECT name FROM `lyricist` WHERE keywords LIKE '%$val%'";


Here $val has 'তোমার,আমার,তুমি' or 'তোমার,তুমি' these type of values.

Why not it's treating the item randomly? Please HELP.

Answer
$query = "SELECT name FROM `lyricist` WHERE keywords LIKE '%$val%'";

Will get you all the matching columns that start with some text having your value and then end with some text.So if you put some random words and they are not in the correct order obviously this query will not match.

I think what you want to do is when you have multiple values is put them in different variable val1,val2,... and using AND in your query

$query = "SELECT name FROM `lyricist` WHERE keywords LIKE '%$val1%' AND keywords LIKE '%$val2%'";

So you would have to construct your query dynamically something like this would work:

<?php
$val="keyword1,keyword2,keyword3";
$keywords=explode(',',$val);
if(!empty($keywords)){
     $query="SELECT name FROM `lyricist` WHERE keywords LIKE '%$keywords[0]%' ";  
        if(count($keywords)>1){
        for($i=1;$i<count($keywords);$i++){
         $query.="AND keywords LIKE '%$keywords[$i]%' ";
            }
       }        
}
?>
Comments