2017-04-11 23 views
1

我是codeigniter的新手,並試圖獲得輸出到我的項目的codeigntier視圖的百分比結果。一旦我解決了這個問題,事情會變得更加順暢。 他是模型功能:php/mysql試圖在codeigniter中輸出單個結果?

<?php 

public function _construct() 
{ 
    $this->load->database(); 
} 

public function percent_specilation1($numstudent) 
{ 
    $query = $this->db->query("SELECT * FROM Student WHERE Student.JRNOption ='1'"); 

    $numstudent = $query->num_rows()/25; 

    if($query->num_rows() > 0){ 
     return $numstudent; 
    } 
    return null; 
} 

?> 

這裏是控制器。

<?php 
class Statscontroller extends CI_Controller { 
public function _contruct(){ 
    parent::_construct(); 
    $this->load->model('Stats_model'); 
} 
public function index(){ 

    //echo "Various stats for the Journalism department:"; 
    $data['Test'] = $this->Stats_model->percent_specilation1($numstudent); 
    } 
    public function view($page = 'Statsview') 
     { 
      if (! file_exists(APPPATH.'views/pages/'.$page.'.php')) 
      { 
        // Whoops, we don't have a page for that! 
        show_404(); 
      } 

      //$data['title'] = ucfirst($page); 

      $this->load->view('templates/header',$data); 
    $this->load->view('Statscontroller/index',$data); 
    $this->load->view('templates/header'); 
    } 
?> 

    Here is the view 
    <html> 
    <h1> Various Statistics for the Journalism department</h1> 

    <?php 
    echo "Percent of students that are undecided:"; 
    echo $Test; ?> 
    </html> 

我在做什麼錯?我一直試圖讓它正確的一個多小時,我只想輸出數據庫查詢的單個結果。任何你可以提供的幫助將是偉大的..請尊重。謝謝!

+1

https://www.codeigniter.com/user_guide/general/models.html – user4419336

+1

https://www.codeigniter.com/user_guide/general/controllers.html#class-constructors – user4419336

+0

問題可以在你的索引中,之前添加$ this-> view()來顯示您創建的視圖。 – wallacesilva09

回答

0

試試這個代碼,我已經更新了一些控制器和模型的代碼,並且在模型查詢中使用student表的主鍵爲student_id

更新型號:

<?php 

public function _construct() 
{ 
    $this->load->database(); 
} 

public function percent_specilation1() 
{ 
    $query = $this->db->query("SELECT (SELECT COUNT(s2.student_id) 
      FROM Student s2 
      WHERE s2.JRNOption='1')*100/COUNT(s1.student_id) AS percentage 
      FROM Student s1"); 

    $result = $query->row_array(); 

    return $result['percentage']; 
} 

?> 

更新控制器:

<?php 
class Statscontroller extends CI_Controller { 
    public function _contruct(){ 
     parent::_construct(); 
     $this->load->model('Stats_model'); 
    } 
    public function index(){ 

     //echo "Various stats for the Journalism department:"; 
     $data['Test'] = $this->Stats_model->percent_specilation1(); 
     $this->load->view('templates/header',$data); 
     $this->load->view('Statscontroller/index',$data); 
     $this->load->view('templates/header'); 
    } 


} 
?> 

希望這會幫助你。