Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

In my db table, I have two datetime columns: Last and Current. These column allow me to keep track of when someone last used a valid login to the service I am building up.

Using CodeIgniter's active record, is it possible to update a row so that the Last value receives the Current value AND then the Current value is replace with the current datetime?

like image 815
chris Avatar asked Sep 09 '13 05:09

chris


People also ask

How do I change the value of a column based on another column?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.

How delete all data from table in CodeIgniter?

Delete function is used to delete the one or more row data from database table. If you want to delete all data from a table, you can use the truncate() function, or empty_table().


2 Answers

Try like this:

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

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'
like image 107
Rajeev Ranjan Avatar answered Oct 06 '22 00:10

Rajeev Ranjan


$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);
like image 35
Praveen PL Avatar answered Oct 05 '22 22:10

Praveen PL