Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.
The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.
To prevent CodeIgniter from doing this "favor" automatically, use the set()
method with a third parameter of 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
The generated query (depending on your database adapter) would be like this:
UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444
Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0
In this case, Last
and Current
ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.
If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().