php - CodeIgniter:将最后一个事件存储到数据库中

标签 php mysql database codeigniter session

我在数据库中创建了两个表,一个包含用户,另一个包含 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/

相关文章:

php - 接受上传的同名文件?

php - Laravel-[PDOException] SQLSTATE[42S02] : Base table or view not found: 1146 Table 'ip.priorities' doesn't exist

php - 无法创建表

php - ZFC Rbac UnauthorizedStrategy 和 Zend Framework 3

php - 从 paypal 付款返回站点期间 mysql 插入查询的问题

.net - ibm.data.informix 没有从数据库中获取正确的数据

php - 如果名称存在则另存为 name(1) name(2) 等等

python - 基于逻辑条件的 Pandas DataFrame 切片?

database - NodeJS 中模型的可选更改

php - 使用 PHP 的下拉菜单