Pass Object from Controller to View in CodeIgniter Framework


Create new folder named assets in root project. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

$config['base_url'] = 'http://localhost:9092/LearnCodeIgniterWithRealApps/';

Create new PHP file named product.php in models folder as below:

<?php defined('BASEPATH') or exit('No direct script access allowed');

class product
{

    var $id;
    var $name;
    var $price;
    var $quantity;
    var $photo;

    function __construct($id, $name, $price, $quantity, $photo)
    {
        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;
        $this->photo = $photo;
    }
}




Create new PHP file named product_model.php in models folder as below:

<?php
if (! defined('BASEPATH'))
    exit('No direct script access allowed');

require 'product.php';

class Product_model extends CI_Model
{

    function find() {
        return new Product('p01', 'name 1', 2, 3, 'thumb1.gif');
    }
}

?>

In CodeIgniter Project, Open autoload.php file in config folder and set value for model config as below:

$autoload['model'] = array('Product_model' => 'productModel');

Create new PHP file named demo.php in controllers folder as below:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Demo extends CI_Controller {

	public function index()
	{
	    $data['product'] = $this->productModel->find();
		$this->load->view('demo/index', $data);
	}

}

In CodeIgniter Project, Open routes.php file in config folder. Set value for default_controller as below:

$route['default_controller'] = 'demo';




Create new folder named demo in views folder. In this folder, create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Demo Page</title>
	</head>
	<body>

		<h3>Product Info</h3>
		<table border="1" cellpadding="2" cellspacing="2">
			<tr>
				<td>Id</td>
				<td><?php echo $product->id; ?></td>
			</tr>
			<tr>
				<td>Name</td>
				<td><?php echo $product->name; ?></td>
			</tr>
			<tr>
				<td valign="top">Photo</td>
				<td><img src="<?php echo base_url(); ?>/assets/images/<?php echo $product->photo; ?>"></td>
			</tr>
			<tr>
				<td>Price</td>
				<td><?php echo $product->price; ?></td>
			</tr>
			<tr>
				<td>Quantity</td>
				<td><?php echo $product->quantity; ?></td>
			</tr>
			<tr>
				<td>Total</td>
				<td><?php echo $product->price * $product->quantity; ?></td>
			</tr>
		</table>


	</body>
</html>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/demo/index

Output

I recommend you refer to the books below to learn more about the knowledge in this article: