Home > Backend Development > PHP Tutorial > How to Determine Query Success in CodeIgniter: Why My Update Query Returns Nothing?

How to Determine Query Success in CodeIgniter: Why My Update Query Returns Nothing?

Mary-Kate Olsen
Release: 2024-10-31 03:02:02
Original
963 people have browsed it

How to Determine Query Success in CodeIgniter: Why My Update Query Returns Nothing?

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');
    }
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template