CodeIgniter模型在我的查询中插入额外的字符

时间:2015-01-25 19:29:22

标签: php codeigniter

我在CodeIgniter模型中执行查询,这是我的代码:

if($query = $this->db->select('postID, users.userID, users.userFirstName, users.userLastName, postTitle, postDescription, postHtmlContent, date_format(creationDate, "%d %b, %Y") as creationDate, date_format(updationDate, "%d %b, %Y") as updationDate, cover, postType')->from('posts, users')->where('users.userID = posts.userID and postID = 1 and postStatus = "APPROVED"')->get()){
            return $query->result()[0];
        }else{
            return NULL;
        }
执行此查询时,

在mysql控制台上正常工作,但是使用CodeIgniter的这个活动记录模板,date_format部分中会引入一些额外的字符。以下是CodeIgniter显示的错误date_format(creationDate,“%d %b,%Y”)part中清晰可见所有额外字符。

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 'FROM (`posts`, `users`) WHERE `users`.`userID` = posts.userID and postID = 1 and' at line 2

SELECT `postID`, `users`.`userID`, `users`.`userFirstName`, `users`.`userLastName`, `postTitle`, `postDescription`, `postHtmlContent`, date_format(creationDate, `"%d` %b, `%Y")` as creationDate, date_format(updationDate, `"%d` %b, `%Y")` as updationDate, `cover`, `postType` FROM (`posts`, `users`) WHERE `users`.`userID` = posts.userID and postID = 1 and postStatus = "APPROVED"

如何解决此问题,我们将不胜感激任何帮助。感谢

2 个答案:

答案 0 :(得分:1)

要删除反引号,必须在选择部分添加第二个可选参数(FALSE):

$this->db->select("postID, userID, . . .", FALSE);

答案 1 :(得分:1)

只需添加false作为select的第二个参数,这样codeigniter就不会转换格式

if($query = $this->db->select('postID, users.userID, users.userFirstName, users.userLastName, postTitle, postDescription, postHtmlContent, date_format(creationDate, "%d %b, %Y") as creationDate, date_format(updationDate, "%d %b, %Y") as updationDate, cover, postType',false)->from('posts, users')->where('users.userID = posts.userID and postID = 1 and postStatus = "APPROVED"')->get()){
        return $query->result()[0];
    }else{
        return NULL;
    }

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.