首页 > 解决方案 > 如何使用不同的数据库表制作注册表单codeigniter

问题描述

我试图在具有不同数据库表的多用户网站上制作注册表单。

例如,当user1 注册时,数据将输入到表“user1”中,当用户2 注册时,将数据输入到表“user2”中。

我只能将 user1 和 user2 输入到同一个表中。这是我使用 role_id 的代码

$data = [
            'name' => htmlspecialchars($this->input->post('nama', true)),
            'username' => htmlspecialchars($this->input->post('username', true)),
            'photo' => 'default.jpg',
            'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
            'role_id' => 2,
            'is_active' => 1,
            'is_date' => time()
        ];

标签: codeigniteruser-rolesmulti-user

解决方案


您可以通过应用条件来做到这一点,role_id但这只有在只有多个用户的情况下才有可能。如果有很多用户并且您想为每个用户创建一个单独的表,请尝试Database Forge Class(不好的做法)

我已经为您的问题编写了一个可能的解决方案,必要时会提到评论。看看对你有没有帮助。

控制器

$data = [
            'name' => htmlspecialchars($this->input->post('nama', true)),
            'username' => htmlspecialchars($this->input->post('username', true)),
            'photo' => 'default.jpg',
            'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
            'role_id' => 2,
            'is_active' => 1,
            'is_date' => time()
        ];

$this->xyz_model->xyz_function($data); // load xyz_model and call xyz_function with $data parameters

xyz_model

function xyz_function($data){

    $table = 'user1'; // default value

    if($data['role_id'] != 1){ // other value is 2 -- assuming only 2 users are there(if not user if else or switch)
        $table = 'user2';
    }

    $this->db->insert($table, $data);

    return $this->db->insert_id();
}

推荐阅读