CodeIgniter Active Record非常简单,文档齐全且功能强大。但是当我尝试插入MySQL内置函数CONCAT
,NOW
,GROUP_CONCAT
,DATEDIFF
,TRIM
等或我的自定义函数时,它会给出错误。以下代码工作正常......
$result = $this->db->select('p.first_name, p.last_name, p.mobile_number, p.email_address')->from('profile p')->get()->result();
但是当我想联系first_name
和last_name
并使用MySQL CONCAT
这样的函数时......
$result = $this->db->select('CONCAT(p.first_name, " ", p.last_name) fullname, p.mobile_number, p.email_address')->from('profile p')->get()->result();
显示数据库错误
A Database Error Occurred
Error Number: 1064
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 '", `p`.`last_name)` fullname, `p`.`mobile_number`, `p`.`email_address` FROM (`pr' at line 1
SELECT CONCAT(p.first_name, `"` ", `p`.`last_name)` fullname, `p`.`mobile_number`, `p`.`email_address` FROM (`profile` p)
Filename: D:\xampp\htdocs\example\system\database\DB_driver.php
Line Number: 330
有没有办法在CodeIgniter Active Record中插入MySQL函数?希望我很清楚。提前谢谢。
答案 0 :(得分:4)
因为我不知道你的确切错误:
来自user_guide:
$ this-> db-> select()接受可选的第二个参数。如果将其设置为FALSE,CodeIgniter将不会尝试使用反引号来保护您的字段或表名称。如果您需要复合选择语句,这非常有用。
$result = $this->db->select('CONCAT(p.first_name, " ", p.last_name) fullname, p.mobile_number, p.email_address', FALSE)->from('profile p')->get()->result();
答案 1 :(得分:1)
将“select”放在数组中 $ this-> db-> select(array('CONCAT(p.first_name,“”,p.last_name)fullname,p.mobile_number,p.email_address'))
通过。
答案 2 :(得分:1)
对于使用活动记录进行更新的情况,您可以使用
$this->db->set("date_read", "NOW()", FALSE);
会输出类似这样的内容
`SET `date_read` = NOW(),
答案 3 :(得分:0)
在活动记录数组中添加字段名称可以解决此问题。在数组内部你可以使用任何mysql函数。上面的解决方案。
MySQL表:
fullname mobile_number email_address
------------------- ------------- ------------------------------
sitaramaiah javvadi 9989403339 gnt.sitaramaiah@mstonline.in
raja kumar guthula 9949526012 gnt.rajkumar@mstonline.in
chandra sekhar k.l 9912144556 gnt.sekhar@mstonline.in
khadar basha 98884884584 khadar333332@gmail.com
super administrator 9841866445 admin@gmail.com
CodeIgniter Active Record:
$result = $this->db->select(array('CONCAT(p.first_name, " ", p.last_name) `fullname`', 'p.mobile_number', 'p.email_address'))->from('profile `p`')->get()->result();
echo '<pre>';
print_r($result);
输出:
Array
(
[0] => stdClass Object
(
[fullname] => sitaramaiah javvadi
[mobile_number] => 9989403339
[email_address] => gnt.sitaramaiah@mstonline.in
)
[1] => stdClass Object
(
[fullname] => raja kumar guthula
[mobile_number] => 9949526012
[email_address] => gnt.rajkumar@mstonline.in
)
[2] => stdClass Object
(
[fullname] => chandra sekhar k.l
[mobile_number] => 9912144556
[email_address] => gnt.sekhar@mstonline.in
)
[3] => stdClass Object
(
[fullname] => khadar basha
[mobile_number] => 98884884584
[email_address] => khadar333332@gmail.com
)
[4] => stdClass Object
(
[fullname] => super administrator
[mobile_number] => 9841866445
[email_address] => admin@gmail.com
)
)