Detecting Query Success in Codeigniter
When executing database queries, it's crucial to determine whether they are successful or not. In your case, the update query within the delete controller method returns nothing, even after changes to the database. To resolve this issue, follow these guidelines:
1. Enhanced Controller Function (Soft Delete)
Avoid passing the user ID via the URL for security reasons. Instead, use $_POST to transfer data during data writes. The revised controller function should look like this:
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'); } }
2. Enhanced Model Method
Perform queries solely in the model. Check the query process at multiple points because a query can have no syntax errors but still make no changes to the database.
public function update(int $userId, array $newData): int { // Prevent modifying the user_id column unset($newData['user_id']); if ($this->db->update('user_tablename', $newData, ['user_id' => $userId])) { $affectedRows = $this->db->affected_rows(); if ($affectedRows) { // Log successful changes if applicable } return $affectedRows; } return 0; }
By following these guidelines, you can effectively determine the success of your database queries and handle both successful and unsuccessful scenarios accordingly.
The above is the detailed content of How to Determine Query Success in CodeIgniter: Why My Update Query Returns Nothing?. For more information, please follow other related articles on the PHP Chinese website!