Vladimir
Vladimir

Reputation: 1622

PHP Function proceeded even after Return

I am using CodeIgniter PHP framework,

In my Model, i have a function like this (simplified):

public function do_stuff($id=FALSE)
{
    // Get all rows from `Table A`
    $result_table_a = $this->db->get('table_a')->result_array();

    // Update `Table B` data
    $update_table_b = $this->db->update('table_b', $data);

    // If failed to update `Table B` return FALSE
    if ( !$update_table_b || $this->db->affected_rows()<1 )
    {
        $this->data['message'] = '<p>Failed to Update (#34)!</p>';
        return FALSE;
    }

    // Update all selected rows from `Table A`
    foreach ($result_table_a AS $result)
    {
        $this->function_to_update_table_a($some_data);
    }
}

Today i was running this function as a user, i saw the error Failed to Update (#34)! but then i noticed the foreach loop has also run and the function inside it has updated table_a as well

Is this possible? can a function continue to work after return?

I am really confused

Upvotes: 1

Views: 61

Answers (1)

Jonathan
Jonathan

Reputation: 2877

Checking to see if any rows were affected is not the correct way to determine if an update was successful. This is because if you try it to update it with the same values it will says no rows were updated.

I will assume that $this->db->update() returns a boolean, as such if you just change your if statement from if ( !$update_table_b || $this->db->affected_rows()<1 ) to this if ( !$update_table_b ) this should solve your problem.

Upvotes: 2

Related Questions