在我的 db 表中,我有两个日期时间列:Last
和Current
. 这些列允许我跟踪某人上次使用有效登录到我正在构建的服务的时间。
使用 CodeIgniter 的活动记录,是否可以更新一行以便该Last
值接收该Current
值,然后将该Current
值替换为当前日期时间?
在我的 db 表中,我有两个日期时间列:Last
和Current
. 这些列允许我跟踪某人上次使用有效登录到我正在构建的服务的时间。
使用 CodeIgniter 的活动记录,是否可以更新一行以便该Last
值接收该Current
值,然后将该Current
值替换为当前日期时间?
试试这样:
$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);
请特别注意set()
调用的第三个参数。 false
防止 CodeIgniter 引用第二个参数——这允许将值视为表列而不是字符串值。对于不需要特殊处理的任何数据,您可以将所有这些声明集中到$data
数组中。
上述代码生成的查询:
UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'
$data = array(
'name' => $_POST['name'] ,
'groupname' => $_POST['groupname'],
'age' => $_POST['age']
);
$this->db->where('id', $_POST['id']);
$this->db->update('tbl_user', $data);
如果您只想升级表格行的单个列,则可以使用如下:
$this->db->set('column_header', $value); //value that used to update column
$this->db->where('column_id', $column_id_value); //which row want to upgrade
$this->db->update('table_name'); //table name
是的,这是可能的,我想为 Rajeev 的答案提供一个轻微的替代方案,它不会将 php 生成的日期时间格式的字符串传递给查询。
关于如何在 UPDATE 查询中声明要设置的值的重要区别是它们不能被引用为文字字符串。
要防止 CodeIgniter 自动执行此“优惠”,请使用set()
带有第三个参数的方法false
。
$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login'); // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows(); // this is expected to return the integer: 1
生成的查询(取决于您的数据库适配器)将如下所示:
UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444
证明查询有效的证据:https ://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0
在这种情况下,Last
和Current
ARE MySQL 关键字,但它们不是保留关键字,因此它们不需要反引号。
如果您的精确查询需要有正确引用的标识符(表/列名),那么总是有protectIdentifiers()。