Question

I have a model update function being called by my controller:

function update_customer_records( $id, $data )
{
    $this->db->where( 'id', $id );
    $this->db->update( 'customers', $data );
}

I am simply updating my table. if the update fails, example duplicate customer name [unique field] I want to send flashdata back to the user $this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate Customer Name. Please try again or contact the administrator');

So something like this:

function update_customer_records( $id, $data )
{
    $this->db->where( 'id', $id );
    $this->db->update( 'customers', $data );

    if(update fails){
    $this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate Customer. Please try again or contact the administrator');
    redirect('masterdata/create_customer', 'refresh');
    } else
    {
    $this->session->set_flashdata('dbaction', 'Update Successful');
    redirect('masterdata/create_customer', 'refresh');  
    }
}

Would this be acceptable or is there a better method for handling this?

Thanks in advance, as always.

Was it helpful?

Solution

YOu can use this. returns true if rows affected by the update are greater than 1 else return false

function update_customer_records( $id, $data)
{
    $this->db->where( 'id', $id );
    $this->db->update( 'customers', $data );

     //if affected rows > 0 reutrn true else false
    return $this->db->affected_rows() > 0 ? TRUE : FALSE;
}

then on your controller you can use it as

if($this->model->update_customer_records() == FALSE)
{
   // set the flashdata here

}else{

  // do what you want if update is successful
}

OTHER TIPS

You can use this in your model:

function update_customer_records( $id, $data ) {    
            $this->db->where( 'id', $id );
            if($this->db->update( 'customers', $data ))
              return true;
            else
              return false;
        }



function is_exist($customer_name)
    {
        $query = $this->db->get_where($customers, array('customer_name' => $customer_name), 1);
        if ($query->num_rows() > 0)
            return false;
        else
           return true; 
    }

and in controller use this:

if($this->model->is_exist($customer_name)
    {
        $this->db->update_customer_records( $id, $data ); 
        $this->session->set_flashdata('dbaction', 'Update Successful');
    }
else
   {
       $this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate  
       Customer. Please try again or contact the administrator');     
    }
    redirect('masterdata/create_customer', 'refresh'); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top