PHP PDO搜索与变音符匹配不起作用

时间:2019-06-29 15:24:44

标签: php mysql search pdo diacritics

我想查询与MariaDB(InnoDB,utf8mb4_unicode_ci)匹配的条目。

它与不带变音符的搜索词一起使用,SQL代码甚至与phpmyadmin上的变音符一起使用。如果我使用变音符号,我会得到一个空数组。

// DB connection
$dboptions = array('charset=utf8mb4'); // with and without: no difference
$pdo = new PDO("mysql:host=$dbservername;dbname=$dbname", $dbusername, $dbpassword, $dboptions);

// Call
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$statement = $pdo->prepare(
"   SELECT
        Date(a_timestamp) AS thedate,
        count(a_timestamp) AS counted,
        a_comb_f
    FROM `$dbtable`
    WHERE Year(a_timestamp) >= '$chartyear'
    AND MATCH (a_comb_f) AGAINST ('+Müller' IN BOOLEAN MODE)
    GROUP BY thedate
    ORDER BY thedate
");
$statement->execute();
$result = $statement->fetchAll();
var_dump($result);

Müller的结果:

  

array(0) {}无法正常工作!

Example的结果:

  

有效!

thedate    | counted | a_comb_f
2008-08-20 | 1       | Test Example Test

纯SQL在phpmyadmin等中正常工作。

SELECT
        Date(a_timestamp) AS thedate,
        count(a_timestamp) AS counted,
        a_comb_f
    FROM `dbs4`
    WHERE Year(a_timestamp) >= '$chartyear'
    AND MATCH (a_comb_f) AGAINST ('+Müller' IN BOOLEAN MODE)
    GROUP BY thedate
    ORDER BY thedate

结果:

  

有效!

背景:

InnoDB, utf8mb4_unicode_ci
a_comb_f   Index   varchar(1000)   utf8mb4_unicode_ci

更新1

Indizes
Schlüsselname   Typ Unique  Gepackt Spalte  Kardinalität    Kollation   Null    Kommentar
a_comb_f    FULLTEXT    Nein    Nein    a_comb_f    141798      Nein

查询的列具有FULLTEXT索引。

Update2

我没有找到任何解决方案,所以我尝试使用mysqli而不是PDO来工作!

$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
    die("Connection Error " . $conn->connect_error);
}
if (!$conn->set_charset("utf8mb4")) {
    printf("Error loading utf8mb4: %s\n", $conn->error);
    exit();
}

$sql = 
"   SELECT
        Date(a_timestamp) AS thedate,
        count(a_timestamp) AS counted,
        a_comb_f
    FROM `$dbtable`
    WHERE Year(a_timestamp) >= '$chartyear'
    AND MATCH (a_comb_f) AGAINST ('+Müller' IN BOOLEAN MODE)
    GROUP BY thedate
    ORDER BY thedate
";
$result = mysqli_query($conn, $sql);
$result = mysqli_fetch_all($result, MYSQLI_ASSOC);

有人可以告诉我为什么它可以与mysqli一起使用而不与PDO一起使用吗?


PS:我知道代码包含漏洞(SQL注入)。它仅用于在localhost上进行测试。

1 个答案:

答案 0 :(得分:0)

如果使用PDO,则必须在DNS(数据源名称)上设置字符集:

$pdo = new PDO("mysql:host=$dbservername;dbname=$dbname;charset=utf8mb4", $dbusername, $dbpassword, $dboptions);
                                                        ^^^^^^^^^^^^^^^

删除行:

$dboptions = array('charset=utf8mb4');