0

遇到 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>
4

3 回答 3

1

将您的视图代码更改为

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

也就是说,替换$data$news

于 2012-08-06T12:25:31.457 回答
0

鉴于做如下

<!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 中用 $news 替换 $data

于 2012-08-06T12:26:00.093 回答
0

假设您有$data数组:

$data['x'] = 1;

如果您将 传递$data给视图,

你可以访问1$x不访问$data['x']

于 2012-08-06T12:27:42.707 回答