3

I have a table named ChatSessions where I keep track of active users in the chatroom. I need to prune expired user sessions from the table every 10 minutes. Using pure php-mysql is plain simple but I'm totally clueless how to convert this into ActiveRecord in CodeIgniter. The plain SQL query is below:

SELECT *
FROM `ChatSessions`
WHERE `SessionExpires` < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )

Can anybody tell me what is the equivalent code in CodeIgniter using ActiveRecord?

2 Answers 2

4

The following code should do it:

// You can use custom strings in the where() function
$where = "SessionExpires < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
// although you may need to set the third parameter to FALSE in order to stop CI from protecting your fields.
$this->db->where($where, null, false);
$this->db->delete('ChatSessions');

You could also try the following (but I don't know if this will work):

$where_condition = "DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
$this->db->where("SessionExpires <", $where_condition, false);
$this->db->delete('ChatSessions');
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think ActiveRecord allows functions on WHERE conditions, the same reason why we need to use set($field,$value) for Select()
The user guide gives this example: $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
2

Converting it to ActiveRecord if you already have the SQL seems like a waste of time. I'd just execute the SQL directly.

$sql = "DELETE FROM ChatSessions 
        WHERE SessionExpires < DATE_SUB( NOW( ) , INTERVAL 10 MINUTE )";
$this->db->query($sql);

1 Comment

Thanks for the reply. Yeah, that crossed my mind but I was trying to steer away from "direct" queries in order to retain some kind of consistency on my code. I still haven't figured out yet how to do with ActiveRecord though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.