This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

✨ Vultr and Linode are back on Cloudways! VIEW PLANS→

How to Pass Data From Controller to View in CodeIgniter

Updated on March 30, 2022

4 Min Read
codeigniter load view

A codeigniter load view is a web page that displays all the elements of the UI. In many cases, the view is often a fragment of the page (such as header, footer, widget areas, and sidebars). In many cases, views can be embedded in other views. One important aspect of views is that views could not be called directly. You need to load the views through a controller. In this tutorial, I will highlight the simple, and yet very important process of how to pass data in a CodeIgniter application deployed on any Web Hosting for PHP.

The CodeIgniter URL Helper comes to use with the divert() function that performs a header redirect to the way you indicate as a parameter. redirect(‘/login/form/’, ‘refresh’); Just make sure you stack the URL Helper earlier to anticipating this to work.

Create a View

Create a new text file and name it cwblogview.php. Save this file in application/views/ directory. Open the file and add the following code to it:

<html>
<head>
        <title>Blog</title>
</head>
<body>
        <h1>Welcome to Blog</h1>
</body>
</html>

Download Tools for Developers Now

We’ll send a download link to your inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

Load the View

Loading a view is usually executed through the following syntax:

$this->load->view('name');

where ‘name’ is the name of the view

Noe creates a controller with the name Blog.php.  This controller will contain the method for loading the view:

<?php
class Blog extends CI_Controller {

    public function index()
    {
        $this->load->view('cwblogview');
    }
}

Once you have created the controller, the URL for the view would be:

Your-domain.com/index.php/blog/

Pass array from the controller to view

Here’s the controller code below. You can paste it inside your controller file or could put it in the controller object.

$data['mega_header'][] = (object) array('title' => 'portfolio image' ,

    'img' => 'https://complete path of image' );

$this->load->view('multiple_array', $data);

Here, objects are shown as an Arrow(->) and arrays as a Brick. You can access any object using the arrow (->) and an array with the Brick [‘..’]. 

So, add the following code in the view file:

<?php

        if (isset($mega_header)){

            foreach ($mega_header as $key) {

                ?>

                <div class="header_item">

                    <img alt="<?php echo($key['title']); ?>" src="<?php echo($key->img); ?>"/>

                </div>

                <?php

            }

        }

        ?>

Improve Your CodeIgniter App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

Load Multiple Views

Within a controller, CodeIgniter could handle multiple calls to the view ($this->load->view()). Check out the following code:

<?php
class Page extends CI_Controller {
    public function index()
    {
        $data['page_title'] = 'title';
        $this->load->view('header');
        $this->load->view('menu');
        $this->load->view('content', $data);
        $this->load->view('footer');
    }

}

Sort Views in Subfolders

It is easy to sort views within subfolders:

$this->load->view(‘directory_name/file_name’);

Add Dynamic Data to Views

The usual route of data transfer from the controller to view is through an array or an object. The usual case is that the array or the object is passed as the second parameter of the view load method (something like the following):

$data = array(
    'title' => 'Title',
    'heading' => 'Heading',
    'message' => ' Message'
);

$this->load->view('cwblogview', $data);

The controller would look like this:

<?php
class Blog extends CI_Controller {

    public function index()
    {
        $data['title'] = "Title";
        $data['heading'] = "Heading";

        $this->load->view('cwblogview', $data);
    }
}

This is what the view file would look like:

<html>
<head>
    <title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>

Create the Loops

Notice that the data array that is passed to the view files could be both simple variables and multi-dimensional arrays. In the case of multi-dimensional arrays, you could set up loops to generate multiple rows. For this, add the following code in the controller:

<?php
class Blog extends CI_Controller
{
    public function index()
    {
        $data['todo_list'] = array('First Object', 'Second Object', 'Third Object');
        $data['title'] = "Title";
        $data['heading'] = "Heading";
        $this->load->view('cwblogview', $data);
    }
}

Next, open up the view file and create a loop:

<html>
<head>
    <title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<ul>
    <?php foreach ($todo_list as $item):?>

    <li><?php echo $item;?></li>

    <?php endforeach;?>
</ul>

</body>
</html>

Returning View as Data

The behavior of this method could be further customized through an optional third parameter. Using this parameter returns data as a string instead of sending it to the browser. This is important if you need to have a dataset for processing. Setting the third parameter to TRUE will return the data. The default behavior is FALSE that sends it to the browser.

Using the third parameter, the syntax would be:

$string = $this->load->view('fileview', '', TRUE);

You might also like: Pass Data From One Function To Another In Same Codeigniter Controller

Conclusion

In this tutorial, I have discussed how to pass data from controller to view in CodeIgniter. This straightforward process is one of the many reasons CodeIgniter is a popular choice for web development. For those seeking a hosting environment optimized for CodeIgniter applications, choosing a CodeIgniter Hosting solution can offer additional benefits, such as pre-configured settings and streamlined deployment processes.

Q: What are the different methods or techniques for passing data in CodeIgniter?

A: In CodeIgniter, there are several methods or techniques available for passing data between different components. These methods include:

  • URL Segments: Data can be passed through the URL as segments using the URI class.
  • GET and POST Parameters: Data can be passed through the HTTP GET and POST methods using the input class or the $_GET and $_POST superglobal arrays.
  • URI Queries: Data can be passed through the query string in the URI using the URI helper functions.
  • Session Data: CodeIgniter provides a session library that allows you to store and retrieve data across multiple requests.
  • Flash Data: Flashdata is a temporary session data that is available only for the next request and then automatically cleared.

Q: Can I pass data from the controller to multiple views in CodeIgniter?

A: Yes, you can pass data from the controller to multiple views in CodeIgniter. You can achieve this by calling the $this->load->view() function multiple times and passing the desired data as an array or object to each view.

Q: Can I use sessions or cookies to pass data in CodeIgniter?

A: Yes, you can use sessions and cookies to pass data in CodeIgniter. Sessions store data across multiple requests for a user, while cookies are stored on the user’s browser. Both methods provide convenient ways to pass data within CodeIgniter.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now