codeigniter中未定义的变量


undefined variable in codeigniter

遇到PHP错误

Severity: Notice
Message: Undefined variable: data
Filename: views/body_view.php
Line Number: 13
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/body_view.php
Line Number: 13

所以我在Codeigniter 中遇到了这个问题

控制器:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');
class Blog extends CI_Controller {
    public function __construct()
    {
    parent::__construct();
    }    
    public function index()
    {
        echo 'Hello World!';
    }
    public function mat()
    {
        $this->load->model('materials_model');
        $data = array();
        $data['news'] = $this->materials_model->get();
        $this->load->view('body_view',$data);
    }

}
?>

型号:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');
class Materials_model extends CI_Model
{
    public function get()
    {
        $query = $this->db->get('materials');
        return $query->result_array();
    }
}
?>

视图:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <meta name="author" content="The Sabotage Rebellion hackers" />
    <title>a</title>
</head>
<body>
<?php foreach ($data as $one):?>
<?=$one['author']?>
<?php endforeach; ?>
</body>
</html>

将视图代码更改为

<?php foreach ($news as $one):?>
<?=$one['author']?>
<?php endforeach; ?>

也就是说,用$news 替换$data

在视图中执行以下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <meta name="author" content="The Sabotage Rebellion hackers" />
    <title>a</title>
</head>
<body>
<?php foreach ($news as $one):?>
<?=$one['author']?>
<?php endforeach; ?>
</body>
</html>

在foreach 中将$data替换为$news

假设$data数组为:

$data['x'] = 1;

如果将$data传递给视图,

您可以访问1作为$x而不是$data['x']