Home  >  Article  >  Backend Development  >  How to Pass Data from a CodeIgniter Controller to a View?

How to Pass Data from a CodeIgniter Controller to a View?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 01:03:31599browse

How to Pass Data from a CodeIgniter Controller to a View?

Passing Data from Controller to View in Codeigniter

Question:

In Codeigniter, I'm trying to pass a variable named $data from the poll controller to the results_view. However, I'm encountering an undefined variable error. Here's the code I'm using:

<code class="php">// ...

public function results()
{
    // ...
    $data = "hello";
    $this->load->view('results_view', $data);
}</code>

Answer:

In Codeigniter, when passing data from a controller to a view, $data should be an array or an object.

To resolve this issue, convert $data into an array:

<code class="php">$data = array(
    'hello' => 'hello',
);</code>

or an object:

<code class="php">$data = (object) array(
    'hello' => 'hello',
);</code>

Then, in results_view.php, access the data as follows:

<code class="php">echo $data->hello;</code>

The above is the detailed content of How to Pass Data from a CodeIgniter Controller to a 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