【问题标题】:How can I detect a create, update, delete query is successful in Codeigniter如何在 Codeigniter 中检测创建、更新、删除查询是否成功
【发布时间】:2013-03-12 02:50:03
【问题描述】:

我目前正在编写这样的控制器方法:

public function delete($user_id) {
    if ($this->input->server('REQUEST_METHOD')=='POST') {
        $result = $this->Crm_user_model->update($user_id,
                                                array('deleted'=>true));
        if($result) {
            add_flash_message('info', 'deleted');
        } else {
            add_flash_message('alert', 'can not delete');
        }
        //redirect('user/view');
    }
} 

但是所有结果都没有返回,甚至数据库(mssql)都被改变了。 如何知道更新查询是否成功?

【问题讨论】:

  • 如果您发布模型update() 函数会有所帮助。 $result 是真还是假将取决于该函数返回的内容。

标签: php sql-server codeigniter


【解决方案1】:

crm_user_model->update()中,根据CodeIgniter的update()函数的输出返回truefalse

if ($this->db->update('mytable', $mydata)) {
    // Do some stuff
    return true;
} else {
    // Do some stuff
    return false;
}

或者,如果您不需要在模型中执行任何其他操作,只需执行以下操作:

return $this->db->update('mytable', $mydata);

【讨论】:

    【解决方案2】:

    我有一个顾虑和一些建议。

    1. 控制器:您不应该通过 url 将 $user_id 值传递给您的 delete 控制器。 (例如site/ci/delete/99)每当您将数据“写入”到数据库/服务器时,您应该只使用$_POST 将数据传输到服务器端。

      public function softDeleteUser(): void
      {
          $userId = $this->input->post('user_id');
          if (!$userId) {
              add_flash_message('alert', 'Required data not supplied');
          } elseif (!$this->Crm_user_model->update($userId, ['deleted' => true])) {
              add_flash_message('alert', 'Failed to soft delete user');
          } else {
              add_flash_message('info', 'Soft deleted user');
          }
      }
      

      如果没有user_id 被POST,那么$userId 将被声明为null

      如果您的数据库架构无法存储布尔值 (true),则通常使用 10 作为布尔等效项。

      在构造条件块时,我更喜欢在成功的结果之前写所有负面/错误/不成功的结果。

      建议在允许软删除用户之前进行用户身份验证/授权检查,以便只有特权用户有权执行此操作。

    2. 模型:您的查询应仅在模型中完成。因为一个查询可能没有语法错误,但也没有对数据库进行任何更改,所以您必须在两点检查过程。

      考虑以下情况:

      1. 传递给控制器​​的$userId在数据库中不存在或
      2. 包含$userId 的行已被“软删除”。

      在这两种情况下,查询都不会失败,但不会有受影响的行。这些是您的脚本与实际不断变化的更新区分开来的相关事件。

      public function update(int $userId, array $newData): int
      {
          // ensure that no one can ever modify the user_id column value
          unset($newData['user_id']);
      
          if ($this->db->update('user_tablename', $newData, ['user_id' => $userId])) {
              $affectedRows = $this->db->affected_rows();
              if ($affectedRows) {
                  // potentially log successful change if your system keeps track of change history
                  // $this->Log->userChange($userId, $newData);
              }
              return $affectedRows;
          }
          return 0;
      }
      

      如果有语法错误,它将在您的错误日志中。

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多