在codeigniter中显示默认值

时间:2013-08-14 05:33:18

标签: php codeigniter

在主页中,应显示所有主题。单击主题时,必须显示其各自的章节。这是第一次,即没有选择主题时,必须显示主题id 1的章节。在下面的代码中,我是否应该从索引调用get_chapters()并使get_chapters()返回章节或其他更好的方法?

class Home extends CI_Controller {

private $data = array();

public function index()
{       
    $this->load->model('subjects_model');
    if($query = $this->subjects_model->get_all()) {
        $data['subjects'] = $query->result_array();
    }       


    $this->load->view('home_view', $data);
}



public function get_chapters($id=null) {

    $this->load->model("chapters_model");

    if(!is_null($id)) {
        $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));
    } else {
        $query = $this->chapters_model->get('chapters');
    }

    if($query) {
        $data['chapters'] = $query->result_array();
    }

    $this->load->view('home_view', $data);      
}

}

2 个答案:

答案 0 :(得分:2)

尝试

public function get_chapters($id=null) {
    $this->load->model("chapters_model");

    if(is_null($id)) {
        $id = 1;   
    }
    $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));

    if($query) {
        $data['chapters'] = $query->result_array();
    }

    $this->load->view('home_view', $data);
}

如果$idnull,则subject id将成为1,它会搜索现有的subject id

答案 1 :(得分:0)

public function index($id=null) 

{

        $this->load->model("chapters_model");

        if(is_null($id)) {
             $id = 1;   
         }

        $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));

        if($query) {
            $data['chapters'] = $query->result_array();
         }

        $this->load->view('home_view', $data);
}