Passing Parameters
Passing parameters is a common requirement in web applications, and CodeIgniter provides a neat and simple way to handle it. In this tutorial, we will see how to pass parameters in CodeIgniter.
Syntax
The syntax to pass parameters in CodeIgniter is as follows:
$this->load->view('viewname', $data);
$data
is an array of parameters that you want to pass.
Example
Let's assume we have a controller named Welcome.php
. Here is an example of how we can pass parameters to the view:
class Welcome extends CI_Controller {
public function index()
{
$data['title'] = "Example Title";
$data['body'] = "Welcome to our website";
$this->load->view('welcome_message', $data);
}
}
In the above example, we have defined a $data
array with two parameters: title
and body
. We are passing this array to the welcome_message
view.
In the welcome_message
view, we can access these parameters like this:
<h1><?php echo $title; ?></h1>
<p><?php echo $body; ?></p>
Explanation
In the example above, we defined an array of parameters ($data
) in the controller method. Then, we passed this array to the view by calling the load->view()
function.
In the view file, we used the parameter variables ($title
and $body
) to display data dynamically.
Use
Passing parameters in CodeIgniter is a necessary practice when we want to display dynamic data in our views. This method is secure and simple to use.
Important Points
- The parameters passed can be accessed in the view using the variable names of the array keys.
- Parameters can be passed to any view from any controller method.
- The method must load the view with the
$data
array as the second parameter.
Summary
Passing parameters is one of the fundamental concepts in web application development. In CodeIgniter, it is done via an array, which is then passed to the view from the controller. These parameters can then be accessed in the view using their corresponding variable names. Passing parameters is an essential practice that helps display dynamic data in our views.