[英]Undefined variable in the template
每當加載控制器時,我都會得到未定義的變量。
這是被調用的控制器的索引函數(第4行),並且每隔一次出現相同的錯誤。
<?php
class Students extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Student_model');
}
public function index() {
$data['view_name'] = 'students/dashboard';
$this->load->view('templates/template_student' , $data );
}
}
模板中錯誤的出處這是template_student模板中代碼的一部分
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?php if ($student->passport_photo == '') { ?>
<img src="<?php echo base_url(); ?>assets/images/sample.jpg" alt="">
<?php } else { ?>
<img src="<?php echo base_url(); ?><?php echo $student->passport_photo; ?>" alt="">
<?php } ?>
<?php if ($this->session->userdata('logged_in')) : ?>
<?php echo $this->session->userdata('first_name') . " " . $this->session->userdata('last_name'); ?>
<?php endif; ?>
<span class=" fa fa-angle-down"></span>
</a>
<ul class="dropdown-menu dropdown-usermenu pull-right">
<li><a href="<?php echo base_url(); ?>students/profile"> Profile</a>
</li>
<li><a href="<?php echo base_url(); ?>students/logout"><i class="fa fa-sign-out pull-right"></i> Log Out</a>
</li>
</ul>
</li>
</ul>
我做錯了什么?
您已經在控制器中加載了一個名為Student的模型,並且在模板中正在訪問$ student變量。 那是兩件事。
您應該執行以下操作:
class Students extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Student_model', 'student');
}
public function index()
{
$student = ... // retrieve the student from db
$data['student'] = $student; // define the variable to be sent to the view
$this->load->view('templates/template_student' , $data );
}
}
控制器變更
<?php
class Students extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Student_model');
}
public function index() {
$data = array();
$data['view_name'] = 'students/dashboard';
$data['student'] = $this->student_model->get_all();
$this->load->view('templates/template_student' , $data );
}
}
然后,您必須在Student_model類中添加get_all()函數,如下所示
function get_all()
{
$this->db->from($this->table);
$query=$this->db->get();
if($query->num_rows()>0){
return $query->result_array();
}
else{
return array();
}
}
$this->table
應該是students表名
現在,我希望您可以在視圖中檢查“ passport_photo”值是否存在
<?php if($student[0]['passport_photo'] == ''){
.
.
.
} ?>
希望對您有幫助。。謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.