【发布时间】:2014-07-22 20:35:14
【问题描述】:
我一直在试图弄清楚如何将查询中的数据加载到数组中。
$query->row() //only brings back a single row of data when there are more entries in the database.
如果我只是在下面的模型代码中使用 foreach 循环和回显,数据只是简单地显示在屏幕上。它不在变量或数组中。只是屏幕上的文字都卡在一起了。
我很难找到一个代码示例来告诉我如何使用
$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
}
}
我的行回显到屏幕上。但是没有控制。因此,在控制我的数据方面的任何帮助将不胜感激。
回答
这终于可以恢复所有结果,而不仅仅是一行。
/**
* 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());
}
【问题讨论】:
-
没有得到想要控制的意思??请打印该数组并添加到问题中
-
在上面的代码中,我的问题只是代码没有返回数组,它将数据库表中的值打印到屏幕上。因此,我没有得到像 Children::__set_state(array('id' => 107) 这样的东西,而是将 107 打印到屏幕上。
-
那么我的问题是,如果它只是要从数据库中回显结果,我该如何控制将它们放在我的视图中?
标签: php mysql arrays codeigniter