因此,我访问数据库以检索员工ID列表,然后获取该员工ID数组,以针对数据库上的另一个表运行查询,该表根据员工ID获取此人的所有信息,但我&#39 ; m只获取语句中的最后一个值,但我需要获取并循环所有这些值。任何人都可以看到我的错误吗?
public function manager_list()
{
$results = array();
$managers = $this->db->query('select `employee_id` from `managers`');
foreach($managers->result() as $row)
{
$employee_id = $row->employee_id;
}
$query = $this->db->query('select `employee_id`, `ssn`, `first_name`, `last_name`, `department`, `title`, `status` from `employees` where `employee_id` = "'.$employee_id.'"');
foreach ($query->result() as $row){
$results[] = array(
'employee_id' => $row->employee_id,
'ssn' => $row->ssn,
'first_name' => $row->first_name,
'last_name' =>$row->last_name,
'department' =>$row->department,
'title' =>$row->title,
'status' =>$row->status,
);
}
return $results;
}
这是使用代码点火器框架。
答案 0 :(得分:2)
如果你在一个查询中做到这一点,你可以缩短它,但是因为你说你必须有两个,这里是你的第二个查询的简短版本,不需要foreach循环:击>
$query = $this->db->query('
select `employee_id`, `ssn`, `first_name`,
`last_name`, `department`, `title`, `status`
from `employees` where `employee_id` = "'.$employee_id.'"');
return $query->result_array();
使用Active Records:
return $this->db
->select('`employee_id`, `ssn`, `first_name`,
`last_name`, `department`, `title`, `status`')
->where(array('employee_id' => $employee_id))
->get('employees')
->result_array();
<击> 撞击> 更新
以下是JOIN的简短版本(替换整个代码):
public function manager_list()
{
return $this->db
->select('e.employee_id, e.ssn, e.first_name,
e.last_name, e.department, e.title, e.status')
->join('managers AS m', 'e.employee_id = m.employee_id')
->where(array('e.employee_id' => $employee_id))
->get('employees AS e')
->result_array();
}
答案 1 :(得分:1)
使用JOIN执行一个查询并执行一个循环 -
public function manager_list()
{
$results = array();
$managers = $this->db->query('SELECT `m`.`employee_id`, `e`.`ssn`, `e`.`first_name`, `e`.`last_name`, `e`.`department`, `e`.`title`, `e`.`status` FROM `managers` AS `m` JOIN `employees` AS `e` ON `m`.`employee_id` = `e`.`employee_id`');
foreach ($managers->result() as $row){
$results[] = array(
'employee_id' => $row->employee_id,
'ssn' => $row->ssn,
'first_name' => $row->first_name,
'last_name' =>$row->last_name,
'department' =>$row->department,
'title' =>$row->title,
'status' =>$row->status,
);
}
return $results;
}