【问题标题】:How to remove extra apostrophe如何删除多余的撇号
【发布时间】:2019-10-04 14:17:31
【问题描述】:

我编写了一个 SQL 查询来为我的项目找到所需的输出。我在正确的输出下工作正常。但是突然开始报错,并且在SQL查询中,有一些额外的撇号。如何解决?

我尝试将查询添加到$this->db->query();,但仍然没有用。

public function getStudentConut($id) {
     $this->db->select('students.id')
            ->from('students')
            ->join('bp','students.pbp = bp.id','left')
            ->where(condition 1)
            ->where(condition 2);
    $query1 = $this->db->get_compiled_select(); 

    $this->db->select('students.id')
            ->from('students')
            ->join('bp','students.dbp = bp.id','left')
            ->where(condition 1)
            ->where(condition 2);
    $query2 = $this->db->get_compiled_select(); 

    $this->db->select('COUNT(id) as stud_count')
       ->from('('.$query1." UNION ALL ".$query2.') X')
       ->group_by('X.id');

    $results = $this->db->get();
    return $results->num_rows();
}

它之前给出了正确的计数。但是没有任何新的更改,它开始报错。

现在我得到错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的 '.id`` WHERE ``bp.some_value`` IS NULL AND ``students.`scho' 附近使用正确的语法

SELECT COUNT(id) as stud_count FROM (SELECT students.id`` FROM ``students`` LEFT JOIN ``bp`` ON ``students.pbp`` = ``bp.id`` WHERE ``bp..其他条件.. UNION ALL SELECT students.idFROMstudents LEFT JOINbpONstudents.dbp=bp.id..some other condition....) X GROUP BYX.id`

【问题讨论】:

  • 我认为这与额外的撇号无关。错误可以表明这一点,但这并不重要。可能是关于 UNION 查询。

标签: mysql codeigniter phpmyadmin


【解决方案1】:

我认为问题(至少对于双 `)是 CodeIgniter 对子查询等不是很好。基本上每次你得到编译后的 select 语句时,它已经有了转义标识符,然后你把它放在最后的 from 语句中,这将在上面添加额外的转义标识符。

`->from('('.$query1." UNION ALL ".$query2.') X')`

不幸的是,与set 等其他方法不同,from 没有第二个参数可让您将转义设置为 false(这是我认为您需要的)。

我建议试试这个:

$this->db->_protect_identifiers = FALSE;
$this->db->select('COUNT(id) as stud_count')
       ->from('('.$query1." UNION ALL ".$query2.') X')
       ->group_by('X.id');
$results = $this->db->get();
$this->db->_protect_identifiers = TRUE;

并且还要查看:->where(condition 2);,由于缺少引号,我很确定它不应该编译。您可能不希望此转义,因此您可以按照以下方式执行->where('condition 2', '', false);https://www.codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where

当所有其他方法都失败时,只需知道 CodeIgniter 对“高级”查询有一些限制,也许您应该使用 $this->db->escape_str(...) 转义用户输入变量和 $this->db->query(...) 以运行 SQL 手动将其写为字符串.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 2023-03-05
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多