codeigniter3:通过get-superglobal更新sql表列

cygmwpex  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(352)

我正在使用codeigniter3和bootstrap开发一个注册和登录应用程序。
在我的“users”表中有一个“active”列,它可以取0或1作为值。

我希望能够通过单击“我的用户”视图中的链接,将用户对应的“活动”列的值从0更改为1(激活用户):

用户视图中的“激活”按钮代码:

<a href="<?php echo base_url(); ?>users/activate/<?php echo $user->id ?>" title="Enable" class="btn btn-success btn-xs activate-btn"><span class="glyphicon glyphicon-ok"></span> Enable</a>

仍然在“用户”视图中,每个表行都有用户的id:

<tr id="<?php echo $user->id ?>">

在我的usermodel中,我有:

public function activateUser($user_id) {
    $query = $this->db->get_where('users', ['id' => $user_id]);
    return $query->row();
}

在我的用户控制器中,我有:

public function activate($user_id) {
    $this->load->model('Usermodel');
    $user = $this->Usermodel->activateUser($user_id);
    if ($user->active == 0) {
        echo 'activate user';
    }   else {
        echo 'user already active';
    }
}

url users/activate/1 返回“用户已激活”,而 users/activate/2 按预期返回“activate user”。作为codeigniter的新手,我尝试了许多导致错误的上述代码版本:

public function activateUser($user_id) {
    $query = $this->db->get_where('users', ['id' => $user_id])->update('users', $data);
    return $query->row();
}

是导致错误的版本之一。
你能告诉我我该怎么修改代码才能使它按要求工作吗?

57hvy0tb

57hvy0tb1#

如果我理解正确,activateuser应该更新该用户的数据库行,然后返回所有更新的用户信息。您正在尝试将两个应该分开的查询混合在一起。分两步进行:

public function activateUser($user_id) {
    $user = null;

    $updateQuery = $this->db->where('id', $user_id)->update('users', ['active' => 1]);
    if ($updateQuery !== false) {
        $userQuery = $this->db->get_where('users', ['id' => $user_id]);
        $user = $userQuery->row();
    }

    return $user;
}

我做了一点错误检查;例如,如果用户id无效,则返回 null .
基于该错误检查,控制器代码可能如下所示:

public function activate($user_id) {
    $this->load->model('Usermodel');
    $user = $this->Usermodel->activateUser($user_id);

    // $user->active will always be 1 here, unless there was an error

    if (is_null($user) {
        echo 'error activating user - check user id';
    } else {
        // I was assuming you would want to do something with the user object,
        // but if not, you can simply return a success message.
        echo 'user is now active';
    }
}

相关问题