skip to Main Content

I’m trying to delete from two tables using one function.

Controller code:

public function userdelete()
    {
        $u_id = $this->uri->segment(3);
                $lr_id = $this->uri->segment(3);
        $returndata = $this->user_model->user_delete($u_id, $lr_id);
               
                
             
        if($returndata) {
            $this->session->set_flashdata('successmessage', 'user deleted successfully..');
            redirect('users');
        } else {
            $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
            redirect('users');
        }
}

Modle code:

public function user_delete($lr_id, $u_id ) { 
        
        
                   return $this->db->delete('login_roles',['lr_id'=>$lr_id]);
           
           
           
                   return $this->db->delete('login',['u_id'=>$u_id]);
               
               
                }

I’m able to delete only from the first table but not the other one. this is working :

return $this->db->delete('login_roles',['lr_id'=>$lr_id]); but not return $this->db->delete('login',['u_id'=>$u_id]);.

2

Answers


  1. It never reaches the second $this->db->delete since its returns after executing the first one. Try:

    public function user_delete($lr_id, $u_id ) { 
        if($this->db->delete('login_roles',['lr_id'=>$lr_id])){
            //success, try the next one      
            return $this->db->delete('login',['u_id'=>$u_id]);
        }
        //failed
        return false;
    }
    
    Login or Signup to reply.
  2. As said in the comment you have to remove the first return.
    You should compute the two results :

    public function user_delete($lr_id, $u_id ) { 
        $delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
        $delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
        return ($delete1Response AND $delete2Response);
    }
    

    It will returns true only if both are deleted

    You even can go further and :

     public function user_delete($lr_id, $u_id ) { 
        $delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
        $delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
        return (object)array('role' => $delete1Response, 'user' => $delete2Response);
     }
    

    Then you can access to data like that :

    $response = user_delete(...);
    if ($response->role AND $response->user) {
        // All fine
    } else {
        // One or both failed.
        // Display error or do something
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search