I've read similar questions and answers on Codeigniter update but not able to solve my problem.
I have a user table and a user_role table. The user table has information like userid, name, address etc and the user_role table has userid and role_id where role_id s are ids for roles such as Entry, Edit, View etc.
Now an admin can change the role of a user and update the user information. The roles are shown as checkboxes. To update the roles of user, I have deleted all the rows for that user in user_role table and inserted new roles. I have tried this:
if(!empty($_POST['role'])) {
$this->db->where('user_id', $id);
$this->db->delete('user_role');
foreach ($_POST['role'] as $val) {
$arr['user_id'] = $id;
$arr['role_id'] = $val;
$this->db->insert('user_role', $arr);
}
}
else {
$this->db->where('user_id', $id);
$this->db->delete('user_role');
}
If all the checkboxes are uncheked, then all the rows are deleted. It is working fine. But this does not seem to be a proper way. Please guide.
if($_POST['role']){
foreach ($_POST['role'] as $val) {
$arr['user_id'] = $id;
$arr['role_id'] = $val;
// You need to run Update query. do not need to delete the records every time.
$where = array('user_id'=>$arr['user_id']);
$this->modelname->updateRecord($tablename,$arr,$where);
//It will update the records on post
}
}
First. Where is $id defined??
Second. Codeigniter has a library that makes not necessary the use of $_POST or $_GET.
Third. Is necessary that one user has more than one role?? I recommend you to use a select like:
<select name="role">
<option value="user">User</option>
<option value="employee">Employee</option>
<option value="admin">Admin</option>
</select>
Maybe you need to use an id of the role in the values of the options... something like
<option value="1">User</option>
<option value="2">Employee</option>
<option value="3">Admin</option>
Fourth. If you want update... why don't you use the update method of the codeigneter ORM. In this way, I had made a file called general_model.php placed on the models folder (are you using this folder and the MVC pattern??) where I have something like a facade between the ORM and the controllers. One of the functions is update:
public function update($tablename, $data, $where)
{
foreach($where as $key=>$value)
$this->db->where($key, $value);
$this->db->update($tablename, $data);
if ($this->db->affected_rows() >= 0) return TRUE;
else return FALSE;
}
An example of use from the controller, for your case (using only one role by user) could be:
$this->general_model->update("users_role", array("role_id"=>$this->input->post("")) , array("user_id"=>$id));
I hope it helps you.
PS: If you want I can pass you the general_model.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.