CodeIgniter passing data to the view

2019-08-08 18:39发布

问题:

I am trying to pass from my controller to the view like so...

public function playerslist()
    {
        $this->load->database();
        $data = $this->db->get('skaters');
        $this->load->helper('url');
        $this->load->view('playerslist', $data);
    }

and in my view...

<?php echo $data; ?>

but I get this error...

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/playerslist.php

Line Number: 76

What am I doing wrong?

What I would like to do with this data is put in a foreach statement and display everything in the $data array

foreach($data as $value => $key){
echo $key . "<br/>";
}

Thanks, J

回答1:

You cannot access $data directly from your view. The $data you pass to your view has to be an associative array. The keys will then be converted to variables in your view.

For example:

$data = array(
    'name' => 'John',
    'bars' => 23
);

$this->load->view('playerslist', $data);

Then, in your view, those will be converted to variables:

<?php echo $name; ?> has <?php echo $bars; ?> bars of chocolate.

If you want to access the data in its original format, pass that into the associative array:

$data = $this->db->get('skaters')->result();
$this->load->view( 'playerslist', array('data' => $data) );


回答2:

based on your question and sample code, I conclude that you want to retrieve data from a table 'skaters' and display it in view.

$this-> db-> get ('skaters'); //not return result object or array

You need to change the code

$ this-> db-> get ('skaters') -> result (); // return object

or

$ this-> db-> get ('skaters) -> result_array (); //return array

check this link http://ellislab.com/codeigniter/user-guide/database/results.html

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Then codeigniter will extract the second parameter using 'extract' function http://php.net/manual/en/function.extract.php

public function playerslist ()
     {
         $ this-> load-> database ();
         $ data = $ this-> db-> get ('skaters') -> result ();
         $ this-> load-> helper ('url');
         $ this-> load-> view ('playerslist', array ('data' => $ data));
     }