Codeigniter 3:通过 GET 超全局更新 Sql table 列

Codeigniter 3: update Sql table column via GET superglobal

我正在使用 CodeIgniter 3 和 Bootstrap.

开发 注册和登录 应用程序

在我的 "users" table 中,我有一个 "active" 列,可以将 0 或 1 作为值。

我希望能够通过单击 中的 link 将与用户对应的 "active" 列的值从 0 更改为 1(激活用户)用户浏览量:

用户视图中的 "Activate" 按钮代码:

<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>

仍在用户视图中,每个table行都有用户的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();
}

在我的 User 控制器中我有:

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 returns "user already active" ,而 users/activate/2 returns "activate user",符合预期。作为 Codeigniter 的新手,我尝试了导致错误的上述代码的多个版本:

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

是导致 错误 的版本之一。

你能告诉我我应该在代码中更改什么才能按预期工作吗?

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

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 无效,这将 return 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';
    }
}