Passing Data from Controller to View in CodeIgniter
In CodeIgniter, passing data from controller to view is essential to display dynamic information on web pages. However, a common error encountered is the "undefined variable" error when attempting to access data in the view.
The issue you are facing typically arises when $data is declared as a variable but not assigned to an array or an object. To resolve this, follow these steps:
Define $data as an Array or Object:
In your results() controller method, define $data as an array or an object. It can contain key-value pairs that represent the data you want to pass to the view.
<code class="php">$data = array( 'title' => 'Results', 'votes' => $this->db->get('votes')->result() );</code>
Load the View with the $data Array/Object:
In the results() method, use the $this->load->view() method to load the results_view with the $data array/object.
<code class="php">$this->load->view('results_view', $data);</code>
Access Data in the View:
In the results_view.php file, you can access the data passed from the controller using the array key names. For example, to output the title property:
<code class="php"><h1><?php echo $title; ?></h1></code>
By following these steps, you can effectively pass data from controller to view in CodeIgniter and avoid the "undefined variable" error.
The above is the detailed content of How to Pass Data from Controller to View in CodeIgniter and Avoid \'Undefined Variable\' Errors?. For more information, please follow other related articles on the PHP Chinese website!