如何将消息从模型传递给控制器​​codeigniter?

时间:2015-11-03 07:05:49

标签: codeigniter

我想在某些条件下将消息变量从codeigniter中的模型传递给控制器​​。但是,当我这样做时,它每次只打印“否”。

模型是

public function add_city() {

    /* Storing form data into an array */
    $data = array(
        'city_name' => $this->input->post('city'),
        'city_overview' => $this->input->post('overview')
    );

    /* Checking if already exist in database */
    $query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
    $count_row = $query->num_rows();

    if ($count_row > 0) {
        $msg = "No";
    } else {
        $this->db->insert('city_tbl', $data);
        $msg = "Yes";
    }
    return $msg;
}

和控制器是

public function addingCity() {
    $this->add_model->add_city();
    var_dump($msg);
    //redirect("/city");
}

4 个答案:

答案 0 :(得分:1)

试试这个

public function add_city() {    

    $city_name = $this->input->post('city');
    $city_overview = $this->input->post('overview');

    $query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
    $result = $query->result_array()
    $count = count($result);

    if(empty($count))
    { 
        $msg = "No";
        return $msg;
    } 
    else{ 

        $data = array( 
            'city_name'=>$this->input->post('city'), 
            'city_overview'=>$this->input->post('overview') );

        $this->db->insert('city_tbl', $data);
        $msg = "Yes";
        return $msg;
    }
}

在控制器中

public function addingCity() {
    $msg = $this->add_model->add_city();
    echo $msg;        
}

将数据传递给视图

public function addingCity() {
    $data['msg'] = $this->add_model->add_city();

    $this->load->view("filename", $data); # ex $this->load->view("index", $data);

}

答案 1 :(得分:1)

您需要为控制器中的$msg分配值

public function addingCity() {
    $msg=$this->add_model->add_city();// assign 
    var_dump($msg);
    //redirect("/city");
}

答案 2 :(得分:1)

试试这个

public function add_city() {

$data = array(
    'city_name' => $this->input->post('city'),
    'city_overview' => $this->input->post('overview')
);

/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" .    $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();

if ($count_row > 0) {
    $msg = "No";
} else {
    $this->db->insert('city_tbl', $data);
    $msg = "Yes";
}
return $msg;
}

在带有get方法的控制器重定向消息 -

public function addingCity() {
    $msg = $this->add_model->add_city();

    redirect("/city?msg=".$msg);
}

最后在视图页

上打印此消息
echo $this->input->get('msg');

答案 3 :(得分:0)

错误在您的控制器功能中

尝试使用此代码

public function addingCity() {
    $msg = $this->add_model->add_city();
    echo $msg;die;
    //redirect("/city");
}