2017-04-06 85 views
0

每當我加載控制器時,我都會收到未定義的變量。模板中的未定義變量

以下是調用控制器的索引函數(第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> 

我做了什麼不對的一部分的一部分嗎?

+0

你傳遞給你什麼數據? –

+0

錯誤與第四行中的$ student變量 –

+0

第一次沒有包含索引函數,對此抱歉。 –

回答

0

您已經在您的控制器中加載了名爲Student的模型,並且在您的模板中您正在訪問$ student變量。 這是2件不同的事情。

你應該做這樣的事情:

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); 
    } 
} 
+0

謝謝,我真的很感激。我的一個朋友給了我他的代碼,但我對codeigniter沒有任何瞭解。然後我通過一些教程,再加上你的解釋讓我明白了事情的真相。 –

0

變化控制器

<?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應該是學生表名

現在,我希望你可以檢查值passport_photo在你的看法類似的東西存在,或者不

<?php if($student[0]['passport_photo'] == ''){ 
    . 
    . 
    . 

    } ?> 

我希望這有助於5月you..thanks!

+0

它工作的伴侶。你甚至讓我的代碼更好,謝謝.. –