Search code examples
codeigniterinsertmessage

Codeigniter after insert success message show in view


I am new in Codeigniter and I need to show success and error message after insert data's in database.

How can I show the message in the view page?

This is my coding:

Model

function addnewproducts($data)
{
    if($data['product_name']!="" && $data['product_qty']!="" && $data['product_price']!="" && $data['date']!="")    
    {
        $res=$this->db->insert('product_list',$data);
        return $this->db->insert_id();
    }
    else
    {
        return false;
    }
}

Controller

function addnewproduct()
    {
        $this->load->model('products');
        $data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
        $data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
        $data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
        $data['datetime']=date('d-m-Y');
        $res = $this->products->addnewproducts($data);
        if($res==true)
        {
            $data['success'] = 'Successful';
            $this->load->view('addproduct',$data);
        }

    }

View

<p><?php echo $success; ?></p>

Solution

  • There are many ways but below is which i recommend:

    Set temp session in controller on success or error:

    $res = $this->products->addnewproducts($data);
    if($res==true)
    {
        $this->session->set_flashdata('success', "SUCCESS_MESSAGE_HERE"); 
    }else{
        $this->session->set_flashdata('error', "ERROR_MESSAGE_HERE");
    }
    

    In View you can display flashdata as below:

    echo $this->session->flashdata('success');
    or 
    echo $this->session->flashdata('error');
    

    Source : Codeigniter official website https://codeigniter.com/userguide3/libraries/sessions.html