在模型中返回单行,将其传递给控制器和视图- Codeigniter


Return a single row in model, pass it to controller and view - Codeigniter

很抱歉发布了这样一个新手问题,但是我在返回单个时遇到了困难行,并将其传递给模型。这是我的模型中的方法:

public function test($user_id)
{
    $query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '.$user_id.'");
    return $query->first_row('array');
}

这里是一个例子,我的控制器与一些其他的返回值从我的模型:

class MY_Controller extends CI_Controller
{
    public $layout;
    public $id;
    public $data = array();
    public function __construct()
    {
        parent::__construct();
        $this->output->nocache();
        $this->load->model('subject_model');
        $this->load->model('user_model');
        $this->load->model('survey_model');
        $this->id = $this->session->userdata('user_id');
        $this->data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
        $this->data['check_if_already_posted_lvis_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('lvis_survey', $this->id);
        $this->data['test']= $this->survey_model->test($this->id);

        $this->layout = 'layout/dashboard';
}

我可以把数据数组中的所有值传递给我的视图,除了"test"。我基本上什么都试过了。

CheckIfAlreadyPostedSurvey方法将返回使用num_rows查询行数,我可以很容易地在我的视图中打印它们的值:

<?=$check_if_already_posted_it_survey?>

我应该怎么做才能在我的视图中打印出"test"?

我可能答错了问题,但是你试过了吗

echo $this->survey_model->test($this->id);

试试这个:

public function test($user_id)
{
    $query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '".$user_id."'");
    return $query->row()->test;
}

这将返回单行作为对象,然后是引用的行名,在本例中是test

下面也可以。

public function test($user_id)
{
    $query = $this->db->query("SELECT * FROM test WHERE user_id = '".$user_id."'");
    return count($query->result());
}

你还弄乱了SQL语句中的引号