Codeigniter 3 对多列使用 db->like 会导致 SQL 相关错误

Codeigniter 3 use of db->like for multiple columns results in an SQL related error

我正在使用 Codeigniter 3.1.8 开发基本的 博客应用程序

搜索帖子 功能给我带来了意想不到的麻烦:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* LIKE '%expression%' ESCAPE '!'' at line 3

SELECT * FROM `posts` WHERE * LIKE '%expression%' ESCAPE '!'

Posts 模型中的 search() 方法如下所示:

public function search($expression) {
    $this->db->like('*', $expression);
    $query = $this->db->get('posts');
    return $query->result();
}

相关的 table 字段是:

我的错误在哪里?

您需要使用 column/expression 而不是 *:

SELECT * FROM `posts` WHERE * LIKE '%expression%' ESCAPE '!'
=>
SELECT * FROM `posts` WHERE column_name LIKE '%expression%' ESCAPE '!';

I need to seelct from all columns in the posts table

然后你可以使用类似的东西(注意性能不佳,因为 CONCATLIKE '%exp' 使其不可 SARGable。

SELECT * FROM `posts` 
WHERE CONCAT(col1,col2, col3, ...)  LIKE '%expression%' ESCAPE '!'

为了避免 CONCAT 的潜在问题,您应该添加分隔符:

SELECT * FROM `posts` 
WHERE CONCAT(col1,'^',col2,'^',col3, ...)  LIKE '%expression%' ESCAPE '!'

在新的 CodeIgniter 版本 (3.1.9) 中,修复了一个不需要的拼写错误......在 system/database/DB_query_builder.php 的第 行#973我相信:

这个: case 'before': $v = "%'{$v}'"; // <- Check here break;

更改为: case 'before': $v = "'%{$v}'"; // <- The fix break;

尝试进行此更改,看看是否能解决您的问题。

已编辑

看到你的代码后,请不要使用 * 作为字段名称,你必须指定用于搜索的字段......例如,如果你想在标题中搜索,描述和内容,您可以这样进行:

$query = $this->db->like('title', $expression)
              ->or_like('description', $expression)
              ->or_like('content', $expression);

然后是您的其余代码。试一试。