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

Mary-Kate Olsen
Release: 2024-10-30 11:23:27
Original
396 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

To access the data in the view, use the following syntax:

<code class="php">//results_view.php
echo $message;</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!