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

public function playerslist()
        $data = $this->db->get('skaters');
        $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

dp198879 可能重复的Codeigniter将数据从控制器传递到视图
接近 8 年之前 回复


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) );
dongshao1873 - 您必须在查询中调用result()。 看我的第二次更新。
接近 8 年之前 回复
dsyct08008 它工作但当我尝试在我的视图中为$ data执行foreach语句时,它返回此conn_idResource id#13 result_idResource id#14 result_arrayArray result_objectArray custom_result_objectArray current_row0 num_rows1 row_data
接近 8 年之前 回复
dongxianshuai8927 谢谢乔,那我怎么去拿我的db->进入视图? 所以我可以显示我的数据
接近 8 年之前 回复

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


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

check this link

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

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