[英]How do I test if my MySQL update query was successful in CodeIgniter?
[英]How can I detect a create, update, delete query is successful in Codeigniter
我目前正在编写这样的控制器方法:
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)被更改。 我怎么知道更新查询成功与否?
在crm_user_model->update()
,根据 CodeIgniter 的update()
函数的输出返回true
或false
:
if ($this->db->update('mytable', $mydata)) {
// Do some stuff
return true;
} else {
// Do some stuff
return false;
}
或者,如果您不需要在模型中执行任何其他操作,只需执行以下操作:
return $this->db->update('mytable', $mydata);
我有一个顾虑和一些建议。
控制器:您不应通过 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
),那么通常使用1
和0
作为布尔值。
在构建条件块时,我更喜欢在成功的结果之前写下所有负面/错误/不成功的结果。
建议在允许软删除用户之前进行用户身份验证/授权检查,以便只有特权用户才有权执行此操作。
模型:您的查询应仅在模型中完成。 由于查询可能没有语法错误,但也不会对数据库进行任何更改,因此您必须在两个点检查该过程。
考虑以下情况:
$userId
在数据库中不存在或$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; }
如果有语法错误,它将在您的错误日志中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.