Home > Article > Backend Development > How can I reliably detect the success of a Create, Update, or Delete query in CodeIgniter?
Detecting the Success of a Create, Update, or Delete Query in CodeIgniter
When performing database operations in CodeIgniter, it's essential to verify their success. Failure to do so may lead to data inconsistency or incorrect results being shown to the user.
Incorrect Approach:
The provided controller method assumes that any non-zero return value from the update() model method indicates success. However, this is not a reliable approach since the model may return non-zero values even when the query fails to update any rows.
Correct Approach:
To properly detect the success of database operations, it's recommended to use the following steps:
Controller:
Model:
Example:
<code class="php">// Controller public function delete($user_id) { if ($this->input->server('REQUEST_METHOD') == 'POST') { $result = $this->Crm_user_model->delete($user_id); if ($result === false) { add_flash_message('alert', 'Failed to delete user'); } else if ($result == 0) { add_flash_message('info', 'User not found or already deleted'); } else { add_flash_message('info', 'User deleted successfully'); } } }</code>
<code class="php">// Model public function delete($user_id) { $this->db->delete('user_table', ['user_id' => $user_id]); return $this->db->affected_rows(); }</code>
Additional Considerations:
The above is the detailed content of How can I reliably detect the success of a Create, Update, or Delete query in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!