Home > Article > Backend Development > How to Verify Successful Database Query Execution in CodeIgniter?
Verifying Successful Query Execution in Codeigniter
In CodeIgniter, verifying whether a database query has been executed successfully is crucial for handling database operations effectively.
Controller Logic
The original controller method handles the deletion of a user based on $user_id. However, it doesn't correctly verify the query's success.
A revised controller method could use $_POST to receive the user ID for security reasons. It also employs a more concise condition block to check for the update's success:
public function softDeleteUser(): void { $userId = $this->input->post('user_id'); if ($userId) { $affectedRows = $this->Crm_user_model->update($userId, ['deleted' => true]); if ($affectedRows > 0) { add_flash_message('info', 'Soft deleted user'); } else { add_flash_message('alert', 'Failed to soft delete user'); } } else { add_flash_message('alert', 'Required data not supplied'); } }
Model Considerations
The model should be responsible for query execution and validating the results. In this case, the update() method checks if any rows were affected by the query:
public function update(int $userId, array $newData): int { // Restrict user_id modification unset($newData['user_id']); $this->db->update('user_tablename', $newData, ['user_id' => $userId]); $affectedRows = $this->db->affected_rows(); if ($affectedRows) { // Optional: Log user change } return $affectedRows; }
This approach ensures that the controller can determine whether the update was successful by verifying the affected rows count returned by the model. Any syntax errors or empty query results will be readily apparent, ensuring accurate feedback to the user.
The above is the detailed content of How to Verify Successful Database Query Execution in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!