Home > Article > Backend Development > Why Does \"Undefined Variable\" Error Occur When Passing Data from CodeIgniter Controller to View?
Question: An undefined variable error appears when attempting to pass data ($data) from the Poll controller to the results_view view. Why does this occur?
Here is the relevant controller code:
<code class="php">public function results() { echo "These are the results"; $data = "hello"; $this->load->view('results_view', $data); }</code>
Answer: The issue stems from $data not being defined as an array or an object, which is required when passing data to a view.
To resolve this, define $data as an array or an object:
<code class="php">$data = array( 'message' => 'hello' );</code>
The modified controller code:
<code class="php">public function results() { echo "These are the results"; $data = array( 'message' => 'hello' ); $this->load->view('results_view', $data); }</code>
To access the data in the view, use the following syntax:
<code class="php">//results_view.php echo $message;</code>
The above is the detailed content of Why Does \"Undefined Variable\" Error Occur When Passing Data from CodeIgniter Controller to View?. For more information, please follow other related articles on the PHP Chinese website!