php - 使用 "LIKE"匹配mysql查询中的多个单词

标签 php mysql search full-text-search

我的应用程序允许搜索文章。因此,当用户输入字符串“articlex”时,查询有效并显示结果,但是当输入多个单词“articlexarticley”时,查询不会显示结果。

目前我正在使用此查询

$querySub = 'SELECT * FROM table WHERE (col1 LIKE "%'.$search_string.'%") OR (col2 LIKE "%'.$search_string.'%") OR (col3 LIKE "%'.$search_string.'%")';

其中$search_string仅包含用户输入

如何使查询也适用于多个单词?

最佳答案

PDO 示例

/* Assume $pdo is already prepared as PDO instance. */

// search query split by spaces
$user_input = 'foo bar baz';

// create string for PDO::prepare()
$sql = 'SELECT * FROM testTable WHERE ';
$wheres = $values = array();
foreach (array_filter(explode(' ', $user_input), 'strlen') as $keyword) {
    $wheres[] = 'col1 LIKE ?';
    $values[] = '%' . addcslashes($keyword, '%_\\') . '%'; // this is escape for LIKE search
}
$sql .= $wheres ? implode(' OR ', $wheres) : '1';

// bind values and execute
$stmt = $pdo->prepare($sql);
$stmt->execute($values);

mysql_** 函数示例(已弃用)

/* Assume $link is already prepared as MySQL resource. */

// search query split by spaces
$user_input = 'foo bar baz';

// create string for mysql_auery()
$sql = 'SELECT * FROM testTable WHERE ';
foreach (array_filter(explode(' ', $user_input), 'strlen') as $keyword) {
    $wheres[] = 'col1 LIKE ' . mysql_real_escape_string(
        '%' . addcslashes($keyword, '%_\\') . '%',
        $link
    );
}
$sql .= !empty($wheres) ? implode(' OR ', $wheres) : '1';

// execute
$result = mysql_query($sql, $link);

关于php - 使用 "LIKE"匹配mysql查询中的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19075212/

相关文章:

php - 如何更改结果集中的列名称并使用修改后的列名称在 PHP 中创建新结果集

php - 管理时区

PHP图片上传功能,保存到一个目录,然后返回保存图片的url

python - 按 Django ORM 分组

mysql - 选择每个字段都包含多个值的语句

php - 需要我的 HTML 搜索表单来搜索在搜索表单上选择的选项,然后显示我的结果?

python - 搜索 Python 列表

php - HTML 表单不工作 - HTML <表单>

php - Codeigniter 3 按月份组织/获取表格数据

ruby-on-rails - SQLite3 "LIKE"或 PostgreSQL "ILIKE"的通用 Ruby 解决方案?