我是CodeIgniter(2.03)的新手,并且遇到以下问题:
这是我的主要模板(视图):
<?php $this->load->view('backOffice/bo_header_in'); ?>
<?php $this->load->view($bo_main_content); ?>
<?php $this->load->view('backOffice/bo_footer_in'); ?>
这是我的模型:
<?php
class Back_office_users extends CI_Model
{
public function getAllUsers ()
{
$query = $this->db->query("SELECT * FROM users");
if ($query->num_rows() > 0) {
foreach ($query->result() as $rows) {
$users[] = $rows;
}
return $users;
}
}
}
这是我的控制者:
<?php
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->is_logged_in();
}
public function index ()
{
$this->load->model('back_office_users');
$users['rows'] = $this->back_office_users->getAllUsers();
$data['bo_main_content'] = "backOffice/dashboard";
$this->load->view('backOffice/bo_template_in', $data, $users);
// if I pass the variable like this it works just fine...
//$this->load->view('backOffice/users', $users);
}
public function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || ($is_logged_in != true)) {
$this->accessdenied();
}
}
public function accessdenied ()
{
$data['bo_main_content'] = 'backOffice/accessdenied';
$this->load->view('backOffice/bo_template', $data);
}
public function logout ()
{
$this->session->sess_destroy();
redirect('backOffice/index');
}
}
仪表板视图如下所示:
<?php
print_r($users);
?>
我收到以下错误:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: users
Filename: backOffice/dashboard.php
Line Number: 9
谁能阐明我该如何解决?我不使用模板就创建了另一个视图,它打印了数组.
解决方法:
您没有将$users变量传递给第二个(嵌套的)视图.
我建议将$users添加到$data数组中,然后在第一个视图中将$users数组传递给嵌入式视图.因此,在您的控制器中:
public function index () {
/* stuff... */
$data['users']['rows'] = $this->back_office_users->getAllUsers();
$data['bo_main_content'] = "backOffice/dashboard";
/* stuff... */
$this->load->view('backOffice/bo_template_in', $data);
}
然后在主视图中:
<?php $this->load->view($bo_main_content, $users); ?>
然后在仪表板视图中:
<?php
print_r($rows);
?>
如您所知,这是因为在主视图中,CodeIgniter将$data的所有元素转换为变量,因此我们将以$users变量结束. $users是一个包含行的数组,因此当我们将$users传递给第二个视图时,第二个视图将$users的所有元素转换为视图变量,因此我们现在可以访问$row.