CI,如何通过数据库中的id获取数据?

时间:2017-05-19 03:06:39

标签: codeigniter

+这是我的模特:

public function call_by_id($where){
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where($where);
        $query = $this->db->get();
        return $query->result();
    }

+我的控制器:

public function index()
    {   
        $data = array();
        $w = '';
        $data['call_id'] = $this->mo_product->call_by_id($w);

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

+我想在视图上调用:

$call_id[$id]->username;

2 个答案:

答案 0 :(得分:0)

  • 在模型中,你把$放在错误的地方。把它作为参数=> call_by_id($where)

  • 在控制器中,$w应该是一个整数,就像你的id值,例如:$w = 1;。而且您不需要写$data = array()

+这是我的模特:

public function call_by_id($where){
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('id', $where);
        $query = $this->db->get();
        return $query->result();
    }

+我的控制器:

public function index()
    {   
        $w = 1; //we need to set value for spesific id
        //we can only call the model's function in controller 
        $data['call_id'] = $this->mo_product->call_by_id($w);

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

+我想在视图上调用:

// view is just to show the data after we call the model's function in controller
print_r($call_id);

尝试一下,希望它可以帮助:)

答案 1 :(得分:0)

尝试这样的事情

public function call_by_id($where){
    $this->db->where('your_column_name', $where);
    $query = $this->db->get($this->table);
    return $query->result_array();
}

在控制器上

public function index()
{   

    $data['results'] = array();

    $w = '1'; // some id

    $data['results'] = $this->mo_product->call_by_id($w);

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

查看

foreach ($results as $result) {
    echo $result['something_from_database'];
}
  

只更新一个值使用row_array();

https://www.codeigniter.com/user_guide/database/results.html#CI_DB_result::row_array

模型

public function call_by_id($where){
    $this->db->where('your_column_name', $where);
    $query = $this->db->get($this->table);
    return $query->row_array();
}

控制器

public function index()
{   

    $w = '1'; // some id

    $caller_data = $this->mo_product->call_by_id($w);

    $data['caller_id'] = $caller_data['caller_id'];

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

查看

<?php echo $caller_id;?>