codeigniter mysql查询中未定义的索引

时间:2014-01-20 18:24:37

标签: php mysql codeigniter

我在codeigniter模型中使用以下mysql查询:

$query = 'SELECT t.*, p.id as project_id, p.name as project_name, p.archive as project_archive
FROM project p
JOIN user_project up ON p.id = up.project AND up.user = '.$user.'
LEFT JOIN (SELECT tmp.* FROM
(SELECT *, IF( @prev <> project_id, @rownum := 1, @rownum := @rownum+1 ) AS rank, @prev := project_id
FROM task t
JOIN (SELECT @rownum := NULL, @prev := 0) AS r 
WHERE user_id = '.$user.' AND status < 3
ORDER BY t.project_id) AS tmp
WHERE tmp.rank <= 1) AS t ON p.id = t.project_id
ORDER BY p.id desc, t.status desc';

    $get = $this->db->query($query);

    if($get->num_rows > 0)
        return $get->result_array();

    return array();

这样可以正常工作,但我现在想从id和name中检索同一个表中的其他列。列名是'archive',我尝试添加

p.archive as project_archive

到第一行的末尾,但当我尝试在视图中使用此变量时,它给出了一个'未定义的索引:project_archive'错误。为了确保我在数据库中拥有一切,我将第一行更改为

$query = 'SELECT t.*, p.id as project_id, p.archive as project_name

并且正如预期的那样,存档值打印为project_name。那么为什么我不能将额外的p.archive添加为project_archive ????我的控制器和视图代码在

下面

控制器:

public function index()
{
    $this->title = 'Dashboard';
    $this->menu = 'users|new_project';

    //Load models
    $this->load->model('project_model');
    $this->load->model('task_model');

    // Load tasks
    $data['tasks'] = $this->task_model->get_user_tasks($this->session->userdata('user'));

    $data['page_title']  = "Dashboard";
    $data['status_arr'] = $this->task_model->get_status_array();

    // Load View
    $this->load->view('dashboard', $data);
}

在视图中,我呼吁以下内容:

$tasks['project_archive'] <!-- undefined index error -->
$task['project_id'] <!-- working as expected -->
$task['project_name'] <!-- working as expected -->

1 个答案:

答案 0 :(得分:0)

哎呀。原来索引未定义的原因是代码需要在foreach循环中提供一个值而不是在foreach循环之外调用并获得一个数组。