Codeigniter将查询加载到数组中

时间:2014-07-22 20:35:15

标签: php mysql arrays codeigniter

我一直在试图弄清楚如何将查询中的数据加载到数组中。

$query->row() //only brings back a single row of data when there are more entries in the database. 

如果我只是在下面的模型代码中使用foreach循环和echo,则数据只会显示在屏幕上。它不在变量或数组中。它只是屏幕上的文字全部卡在一起。

我很难找到一个能够告诉我如何使用

的代码示例
$this->db->get_where('table' array('column' => $var);

我终于找到了它,但是然后codeigniters网站上的示例只回显到屏幕上的查询。

  

http://ellislab.com/codeigniter/user-guide/database/results.html

这对于制作没有用。 我的控制器代码是:

    public function record(){ 
        /*
         * Here the id is being passed to the record
         * function to retieve the parent and childrens data
         * 
         */
        $getid['id'] = $this->uri->segment(3);
        $accld = $getid['id'];

        $data = array();

        $this->load->model('account');
        $account = new Account();
        $account->load($getid['id']);
        $data['account'] = $account;

        $this->load->model('children');
        $children = new Children();
        $children->accld($getid['id']);
        $data['children'] = $children;

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

    }


}

我的模型代码是这样的:

public function accld($id) 
{
    $query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));

    $c_data = array();
    foreach ($query->result() as $row){
         $c_data[] = $row ; 
    }
    return $c_data;

    /*
     * Note:
     * I need to figure out how to load to an array to pass back to the 
     * controller to pass to the display
     * I can echo to the screen the results but that is uncontrolled.
     * 
     */
}

如果我这样做:

public function accld($id) 
{
    $query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));

    foreach ($query->result() as $row){
        echo $row->id ;
        // and all the other fields below here 
    }

}

我的行回显到屏幕上。但是没有控制权。因此,非常感谢任何帮助控制我的数据。

ANSWER

这最终会带来所有结果,而不仅仅是一行。

/**
 * Populate from an array or standard class.
 * @param mixed $row
 */
public function populate($row) {
    foreach ($row as $key => $value) {
        $this->$key = $value;
    }
}

public function accld($id) {

    $query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));

    $this->populate($query->result());
 }

1 个答案:

答案 0 :(得分:1)

只做

$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$_array = $query->result_array();

用$ _array做任何事。