[求助]往数据库中插入当前时间
往数据库中插入当前时间,用now()函数,可sql语句就自动给now()加上'',号,怎么办?我做的流程是:
$arr['uname']='aaaaaaaaaa';
$arr['times']='now()';
模型中
$this->db->insert('tbname',$arr); 用 PHP 函数取得日期以后再传给数据库。 $arr['times']='now()';
别加引号应该就可以,加上引号就变成字符串了 jxh163 发表于 2008-6-12 17:50 static/image/common/back.gif
$arr['times']='now()';
别加引号应该就可以,加上引号就变成字符串了
不加引号就会被php解析;用active record类来进行时间插入是不行的,这个应该算是个bug吧。
在active record类对传入的$data参数会进行下面的处理
/**
* The "set" function.Allows key/value pairs to be set for inserting or updating
*
* @param mixed
* @param string
* @param boolean
* @return object
*/
public function set($key, $value = '', $escape = TRUE)
{
$key = $this->_object_to_array($key);
if ( ! is_array($key))
{
$key = array($key => $value);
}
foreach ($key as $k => $v)
{
if ($escape === FALSE)
{
$this->ar_set[$this->_protect_identifiers($k)] = $v;
}
else
{
$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
return $this;
}
然后执行mysql driver中的_insert方法
function _insert($table, $keys, $values)
{
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
}
可以看到都没有对now()进行转义处理。
所以要插入时间时,可以自己手写sql进行插入
$sql = "insert into test(test_date) values (now())";
$this->db->query($sql);
jinphen 发表于 2013-8-9 10:48 static/image/common/back.gif
不加引号就会被php解析;用active record类来进行时间插入是不行的,这个应该算是个bug吧。
在active rec ...
set 的 $escape = false 就可以了。
本帖最后由 jinphen 于 2013-8-10 16:00 编辑
Hex 发表于 2013-8-9 17:24 static/image/common/back.gif
set 的 $escape = false 就可以了。
但在CI_DB_active_record类中,insert方法并没有提供$escape这个参数
如下:
/**
* Insert
*
* Compiles an insert string and runs the query
*
* @param string the table to insert data into
* @param array an associative array of insert values
* @return object
*/
function insert($table = '', $set = NULL)
{
if ( ! is_null($set))
{
$this->set($set);
}
if (count($this->ar_set) == 0)
{
if ($this->db_debug)
{
return $this->display_error('db_must_use_set');
}
return FALSE;
}
if ($table == '')
{
if ( ! isset($this->ar_from))
{
if ($this->db_debug)
{
return $this->display_error('db_must_set_table');
}
return FALSE;
}
$table = $this->ar_from;
}
$sql = $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
$this->_reset_write();
return $this->query($sql);
}
或许不要使用数组方式,而改为用set方式可以把插入时间:
$this->db->set('tmp_date', 'now()', false);
$this->db->insert('mytable');
jinphen 发表于 2013-8-10 15:53 static/image/common/back.gif
但在CI_DB_active_record类中,insert方法并没有提供$escape这个参数
如下:
是的,要改用 set 方法,不能直接用 insert 方法了。
页:
[1]