使用 CodeIgniter 的 Active Record 将 NOW() 插入数据库 [英] Inserting NOW() into Database with CodeIgniter's Active Record

查看:31
本文介绍了使用 CodeIgniter 的 Active Record 将 NOW() 插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Codeigniter 的活动记录中使用 mySQL 函数 NOW() 在数据库中插入当前时间.以下查询无效:

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);

这是因为 CodeIgniter 的 ActiveRecord 类会自动转义输入.

This is because CodeIgniter’s ActiveRecord class automatically escapes the input.

以下工作正常,通过调用 set() 并传递 peratmeter FALSE,这样它就不会转义 NOW().

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."

在这种情况下的基本问题是,您正在调用 MySQL 函数而实际上并未设置值.CI 对值进行转义,以便您可以进行干净的插入,但它不会测试这些值是否恰好调用了诸如 aes_encryptmd5 或(在这种情况下)之类的函数) now().虽然在大多数情况下这很好,但对于这些情况,原始 sql 是唯一的资源.

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.

另一方面,date('Y-m-d'); 应该作为 MySQL 的 NOW() 的 PHP 版本工作.(虽然它不适用于所有版本的 SQL).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆