MySQL MATCH反对完整的文本搜索不能动态地使用php PDO bindParam

时间:2018-05-15 01:15:51

标签: php mysql pdo

我在我的网站上使用jQuery UI实现了一个ajax自动完成搜索,并且它做得很好,但是我遇到了一个不想工作的选择的问题。

database中的autocomplete_search_name字段已经为FULLTEXT index

下面的select在静态模式下工作正常,这就是我希望搜索工作的方式,**

    $stmt = $this->db->prepare("SELECT autocomplete_search_name as label, url as the_link FROM product WHERE status = 'active' AND MATCH(autocomplete_search_name) AGAINST('*psico*' IN BOOLEAN MODE) ORDER BY MATCH(autocomplete_search_name) AGAINST('*psico*') DESC LIMIT 10");
    $stmt->execute();
    $moddados = $stmt->fetchAll();
    return $moddados;

但是,当我开始使用PDO bindParam或PDO引用动态插入参数时,如下例所示,select不再起作用。我研究了很多,但找不到解决这个问题的方法。

    $data['query'] = '*'.$data['query'].'*';
    $stmt = $this->db->prepare("SELECT autocomplete_search_name as label, url as the_link FROM product WHERE status = 'active' AND MATCH(autocomplete_search_name) AGAINST(:query IN BOOLEAN MODE) ORDER BY MATCH(autocomplete_search_name) AGAINST(:query) DESC LIMIT 10");
    $stmt->bindParam(':query', $data['query']);
    $stmt->execute();
    $moddados = $stmt->fetchAll();
    return $moddados;

我在下面尝试过这种方式,但它也不起作用:

$stmt = $this->db->prepare("SELECT autocomplete_search_name as label, url as the_link FROM product WHERE status = 'active' AND MATCH(autocomplete_search_name) AGAINST(CONCAT('*', :query, '*') IN BOOLEAN MODE) ORDER BY MATCH(autocomplete_search_name) AGAINST(CONCAT('*', :query, '*')) DESC LIMIT 10");
    $stmt->bindParam(':query', $data['query']);
    $stmt->execute();
    $moddados = $stmt->fetchAll();
    return $moddados;

并且这种方式也不起作用

$stmt = $this->db->prepare("SELECT autocomplete_search_name as label, url as the_link FROM product WHERE status = 'active' AND MATCH(autocomplete_search_name) AGAINST(':query' IN BOOLEAN MODE) ORDER BY MATCH(autocomplete_search_name) AGAINST(':query') DESC LIMIT 10");
    $stmt->bindParam(':query', '*' . $data['query'] . '*');
    $stmt->execute();
    $moddados = $stmt->fetchAll();
    return $moddados;

1 个答案:

答案 0 :(得分:0)

这是因为你在单引号中有Sync因此MySQL将其视为字符串,而不是参数。

您可以通过将:query替换为'*:query*'并将绑定更改为:

来解决此问题
:query

或者您可以将$stmt->bindParam(':query', '*' . $data['query'] . '*'); 替换为'*:query*'

您可能也遇到限制(请参阅manual)在一个查询中使用相同的参数名称两次(仅当您未使用模拟的预准备语句时才会发生)。在这种情况下,您需要按如下方式更改代码:

CONCAT('*', :query, '*')