Home  >  Article  >  Backend Development  >  Why Does \"Undefined Variable\" Error Occur When Passing Data from CodeIgniter Controller to View?

Why Does \"Undefined Variable\" Error Occur When Passing Data from CodeIgniter Controller to View?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 11:23:27396browse

Why Does

Codeigniter Data Transference from 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn