PDO准备语句并以布尔模式匹配

时间:2017-01-22 21:11:23

标签: php mysql pdo

如果我通过直接输入

从控制台运行这个简单的查询
 SELECT COUNT(*) AS total FROM articles WHERE MATCH(title) AGAINST ('+php +mysql' IN BOOLEAN MODE)

我得到了很多结果。 现在我正在尝试在php中准备这个语句。

$keywords = ['php', 'mysql'];
$against = '';
for($i = 0; $i < count($keywords); $i++){
    $against .= '+? ';  
}
$query = 'SELECT COUNT(*) AS total FROM articles WHERE MATCH(title) AGAINST ('.$against.' IN BOOLEAN MODE)';

//my query is now 'SELECT COUNT(*) AS total FROM articles WHERE MATCH(title) AGAINST (+? +?  IN BOOLEAN MODE)'

$stmt = $pdo->prepare($query);
$stmt->execute($keywords);

如果仅使用1个关键字,则此脚本仅返回结果。使用2个关键字,它不返回任何值,也没有错误(但在控制台中有效)。所以我怀疑这是我用pdo准备语句的方式。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你应该简单地创建一个这样的语句:

$query = 'SELECT COUNT(*) AS total FROM articles WHERE MATCH(title) AGAINST (:query IN BOOLEAN MODE)';
$stmt = $pdo->prepare($query);

然后绑定params:

$keywords = ['php', 'mysql'];
$against = '';
for($i = 0; $i < count($keywords); $i++){
    $against .= ' +' . $keywords[$i];   
}
$stmt = $pdo->prepare(array(
    ':query' => $against
));