Codeigniter data not being passed from controller to view [duplicate]

不羁的心 提交于 2020-01-05 08:32:00

问题


I have setup a codeigniter environment. I am able to pass data from my welcome controller to a view, but I created a new controller called TestController, and I cannot pass data to my test view. It says undefined variable.

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/gallery.php

Line Number: 4

Controller

<?php

class Testcontroller extends CI_Controller {


    // --------------------------------------------------------------------

    /**
     *  The constructor
     */
    function __construct()
    {
        parent::__construct();  



    }


    function index() {


    $data = array('title' => 'My Title',
              'heading' => 'My Heading',
              'message' => 'My Message');

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

    }
}

?>

test view

<?php   var_dump($data); ?> 


回答1:


$data doesn't exist in the view. Instead you have one variable per key in the given array $data. So, in your case you have $title, $heading and $message.

Bear in mind that the passed data could be an anonymous array:

$this->load->view('test', array('title' => 'My Title',
              'heading' => 'My Heading',
              'message' => 'My Message'));



回答2:


You don't need to access the $data array in the view. Access the keys directly:

var_dump($title);



回答3:


In the view you can print like this:

<?php echo $title; ?>
<?php echo $heading; ?>
<?php echo $message; ?>



回答4:


Quick tip -- Do not include the closing php tag in your Controllers or Models !

} // bracket that closes class

 // NO NO NO
?>  

Can mess up the files. the controller or model should end with the class closing bracket. you can put a comment if you want

} // heres a comment and its ok

Whereas in your view files - always close your php code.



来源:https://stackoverflow.com/questions/17956512/codeigniter-data-not-being-passed-from-controller-to-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!