Boolean Mode Where Match Query with Dynamic Agains

2019-06-03 11:12发布

问题:

I want to query mysql with a Where Match query using mysqli prepared statements. The problem is the Boolean Mode AGAINST values,

normally: (+value1 +value2 +value IN BOOLEAN MODE)

but the problem is that I can't use it in prepared statements e.g. (? ? ? IN BOOLEAN MODE) because the number of values will differ, its not fixed.

I tried this code:

$keywords = explode(" ", $SearchResults->squery);   
foreach($keywords as $key=>$value)
{
    $keywords[$key] = '+'.$value;
}
$keywords = implode(",", $keywords);
$dbconnect = new mysqli($host, $user, $pw, $db);
$stmt = $dbconnect->prepare("SELECT `postid` FROM `espina5_jotecodb`.`posttd` WHERE MATCH (`title`) AGAINST (? IN BOOLEAN MODE)"); 
$stmt->bind_param('s', $keywords)
if($stmt->execute())
{
    $stmt->bind_result($col1);
    while ($stmt->fetch()) 
    {
        echo $col1."<br>";
    }
}
$dbconnect->close();

$keywords during bind_param will have a single string containing +value1 +value2 +value3

The problem with the above code is that its not reading the values individually but as a whole, i think its because of the single ? when the statement was prepared and single s during bind. I assumed I could do it like that, guess I was wrong.

So anyway the above code will result in reading the first value and disregard the succeeding values because the value is treated as a single value. So I am asking how can I achieve prepared statement queries with dynamic values for the boolean mode? Should I resort to querying the database individually per value?

回答1:

You are doing it just wrong way.

normally: (+value1 +value2 +value IN BOOLEAN MODE)

it is not. Normally it have to be

('+value1 +value2 +value' IN BOOLEAN MODE)

In quotes and without commas

the same goes with using placeholders: you have to assemble your search string in PHP, and then bind it whole via single placeholder.