Codeigniter更新了SQL问题

时间:2018-12-07 23:40:24

标签: php mysql sql codeigniter

从codeigniter 3.1.0更新到3.1.9后,当前网站的模块出现了一些问题,查看它输出的SQL,这是由于order_by部分所致,但是我从SQL错误中可以看到一些错误将会添加很多`,但是不知道如何解决此输出。

代码块出现问题:

interface IssueFlags
{
 const FLAG_NONE       = 0x000;
 const FLAG_PINNED     = 0x001;        // issue is pinned, will always stick to the top of other issues
 const FLAG_PRIVATE    = 0x002;        // issue is limited only to staff and are not visible for others
 const FLAG_LOCKED     = 0x004;        // issue is locked and is not editable by anyone, only staff are allowed to edit
 const FLAG_CLOSED     = 0x008;        // issue is not opened to comments anymore, only staff are allowed to comment
}

public function get($id = false, $limit = false)
{
    if($id = array_filter((array)$id, 'is_numeric'))
        $this->db->where_in('bugtracker_issues.id', $id);

    if(is_numeric($limit) && !empty($limit))
        $this->db->limit($limit);
    elseif(is_array($limit) && count($limit) == 2)
        $this->db->limit($limit[0], $limit[1]);

    // Limit columns to get proper data and prevent duplicate columns name overwrite eachother
    $this->db->select('bugtracker_issues.*, account_data.nickname');

    // Also join a few columns of account data, so we won't need to query for each user too
    $this->db->join('account_data', 'bugtracker_issues.author = account_data.id', 'left');

    // This allow us to use functions when bulding our query
    $this->db->protect_identifiers = false;

    // Sort issues by update then created timestamp, at the end their id and descending, pinned ones always comes first
    $this->db->order_by('`flags` & ' . self::FLAG_PINNED . ' DESC, IFNULL(`update`, `create`) DESC, `id` DESC');
    $this->db->protect_identifiers = true; // turn it off, as its default state is disabled

    $query = $this->db->from('bugtracker_issues')->get();
    if(!$query || !is_object($query))
        return false;

    if(!$query->num_rows())
        return array();

    return $query->result_array();
}

正在发生的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 DESC, IFNULL(`update`, `create`) DESC, `id` DESC LIMIT 20' at line 4

SELECT `bugtracker_issues`.*, `account_data`.`nickname` FROM `bugtracker_issues` LEFT JOIN `account_data` ON `bugtracker_issues`.`author` = `account_data`.`id` ORDER BY `flags`` &` 1 DESC, IFNULL(`update`, `create`) DESC, `id` DESC LIMIT 20

1 个答案:

答案 0 :(得分:0)

您的ORDER BY子句无效。

ORDER BY `flags`` &` 1 DESC, IFNULL(`update`, `create`) DESC, `id` DESC LIMIT 20

这在SQL中没有意义。

您需要修复PHP代码的一部分以生成正确的ORDER BY子句:

$this->db->order_by('`flags` & ' . self::FLAG_PINNED . ' DESC, IFNULL(`update`, `create`) DESC, `id` DESC');

应写为:

$this->db->order_by('`flags` DESC, IFNULL(`update`, `create`) DESC, `id` DESC');