Create New Post

CodeIgniter - Passing data from Controllers to Views

In CodeIgniter, passing data from controllers to views is a common task when you want to display dynamic content in your web application. Here's how you can pass data from controllers to views:

1. Loading Views with Data:

  • After processing a request in a controller method, load the corresponding view using the load->view() method.
  • Pass data to the view as an associative array as the second parameter of the load->view() method.

Example:

public function index() {
    // Load model if needed
    $this->load->model('example_model');
    
    // Retrieve data from model or other sources
    $data['user'] = $this->example_model->get_user_data($user_id);
    $data['products'] = $this->example_model->get_products();
    
    // Pass data to view
    $this->load->view('example_view', $data);
}

2. Accessing Data in Views:

  • In the corresponding view file (example_view.php), you can access the passed data using PHP variables.
  • Use PHP syntax to echo or manipulate the data within the HTML markup.

Example:

<!-- example_view.php -->
<html>
<head>
    <title>Example View</title>
</head>
<body>
    <h1>Welcome, <?php echo $user['username']; ?>!</h1>
    
    <h2>Products</h2>
    <ul>
    <?php foreach ($products as $product): ?>
        <li><?php echo $product['name']; ?> - $<?php echo $product['price']; ?></li>
    <?php endforeach; ?>
    </ul>
</body>
</html>

3. Using Data in Views:

  • Once the data is passed to the view, you can use it to dynamically generate HTML content.
  • Use PHP control structures like foreach, if, and else to iterate through arrays and conditionally display content.

4. Best Practices:

  • Avoid performing complex business logic or database queries directly in views. Use models for data retrieval and manipulation.
  • Sanitize and validate data before passing it to views to prevent security vulnerabilities.
  • Keep views clean and focused on presentation logic. Minimize PHP logic within views to improve readability and maintainability.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

62142