How to Display Error Message in CodeIgniter

Submitted by: 
Language: 

In this tutorial, I will explain on how to you can display error messages using CodeIgniter into your View from a Controller.

There are two kinds of approach of doing this. First, passing the data directly from Controller to View. Second, using flashdata.

This code is useful, for example, if you have a shopping cart application. Say you want to display an error message telling your visitor that the cart is empty.

First approach:

To do this, add the following in your Controller:

  1. if (!$this->cart->contents())
  2. {
  3. $this->data['err_message'] = 'Your cart is empty!';
  4. }
  5.  
  6. $this->load->view('templates/header', $this->data);
  7. $this->load->view('bookings', $this->data);
  8. $this->load->view('templates/footer');

err_message will become a variable once it is passed into your View called "bookings".

  1. div id="infoMessage"><?php echo $err_message;?></div>

In your booking view, add the following code:

Second approach:

We will use set_flashdata function to display the error message when the page is being redirected.

  1. if (!$this->cart->contents())
  2. {
  3. $this->session->set_flashdata('err_message', 'Your cart is empty!');
  4. }
  5.  
  6. redirect('/bookings');

In your bookings page, add the following code:

  1. <div id="infoMessage"><?php echo $this->session->flashdata('err_message');?></div>

flashdata is different on the first approach since it will only display the error when it was redirected from other page.


Comments

Please tell me hoe to make my codeiginiter website live as it is very well running on local host

Hi,

Are you serious? You are not talking about error message but the way to pass a message you've created to the view. With this kind of title I was expecting to find out how to display real error message in order to debugg a developping issue. Please change your title, the content has not really the same meaning.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.