我在数据库中创建了两个表,一个包含用户,另一个包含 session 。我认为将最后一个事件存储到 session 中不会有任何问题,但后来我发现 session 正在删除并且我无法存储最后一个事件。因为我想将最后的事件存储在某个地方,所以我需要一个解决方案,如何在大约五分钟内将其保存到用户表中 - 与 CodeIgniter 更改它的 session 数据相同。
那么,该怎么做呢?
最佳答案
忘记 session 表,只需在每次请求时更新用户表。我会在基本 Controller 的构造函数中执行此操作,以便它自动运行(如果您对此不熟悉,请参阅 MY_Controller
examples)。像这样:
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct():
// The session class is available now because
// we called the parent constructor, where it is already loaded.
// Get the current logged in user (however your app does it)
$user_id = $this->session->userdata('user_id');
// You might want to validate that the user exists here
// If you only want to update in intervals, check the last_activity.
// You may need to load the date helper, or simply use time() instead.
$time_since = now() - $this->session->userdata('last_activity');
$interval = 300;
// Do nothing if last activity is recent
if ($time_since < $interval) return;
// Update database
$updated = $this->db
->set('last_activity', now())
->where('id', $user_id)
->update('users');
// Log errors if you please
$updated or log_message('error', 'Failed to update last activity.');
}
}
要使用此基本 Controller ,您需要使用其他 Controller 扩展它。示例:
class SomeController extends MY_Controller {
// MY_Controller constructor runs automatically
function index()
{
// your code
}
}
您可以在最初获取登录用户的同一位置执行此操作。
关于php - CodeIgniter:将最后一个事件存储到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368995/