使用CodeIgniter的Active Record将NOW()插入数据库 [英] Inserting NOW() into Database with CodeIgniter's Active Record
问题描述
我想在Codeigniter的活动记录中使用mySQL函数NOW()在数据库中插入当前时间。以下查询将不起作用:
$ data = array(
'name'=> $ name,
'email'=> $ email,
'time'=> NOW()
);
$ this-> db-> insert('mytable',$ data);这是因为CodeIgniter的ActiveRecord类自动转义输入。
$ b
$ b
以下工作正常,通过调用set()和传递peratmeter FALSE,以便它不逃脱NOW()。
$ data = array(
'name'=> $ name,
'email'=> $ email,
);
$ this-> db-> set('time','NOW()',FALSE);
$ this-> db-> insert('mytable',$ data);
但是,我的问题是有没有其他方法?例如,如果我可以使用某种方式使用通过添加数据数组中的所有东西?
例如:
$ data = array(
'name'=> $ name,
'email'=> $ email,
'time'=> NOW(),FALSE
);
除非我大错,否则答案是不,没有办法。
这种情况下的基本问题是,你正在调用一个MySQL函数,你并没有真正设置一个值。 CI转义值,所以你可以做一个干净的插入,但它不测试看看这些值是否正在调用函数 aes_encrypt
, md5
,或(在这种情况下) now()
。
在一边, date('Ym-d' );
应该用作MySQL的 NOW()
的PHP版本。 (它不会工作在所有版本的SQL虽然)。
I want to insert current time in database using mySQL function NOW() in Codeigniter's active record. The following query won't work:
$data = array(
'name' => $name ,
'email' => $email,
'time' => NOW()
);
$this->db->insert('mytable', $data);
This is because CodeIgniter’s ActiveRecord class automatically escapes the input.
The following works fine, by calling set() and passing peratmeter FALSE, so that it doesn't escape the NOW().
$data = array(
'name' => $name ,
'email' => $email,
);
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
However, my question is that is there any other way than this? For example, if i can use somehow use by adding everything in the data array only? For example, something like:
$data = array(
'name' => $name ,
'email' => $email,
'time' => NOW(), FALSE
);
Unless I am greatly mistaken, the answer is, "No, there is no way."
The basic problem in situations like that is the fact that you are calling a MySQL function and you're not actually setting a value. CI escapes values so that you can do a clean insert but it does not test to see if those values happen to be calling functions like aes_encrypt
, md5
, or (in this case) now()
. While in most situations this is wonderful, for those situations raw sql is the only recourse.
On a side, date('Y-m-d');
should work as a PHP version of NOW()
for MySQL. (It won't work for all versions of SQL though).
这篇关于使用CodeIgniter的Active Record将NOW()插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!