遇到查询问题

时间:2013-06-07 04:26:12

标签: codeigniter

我是CodeIgniter的新手,遇到查询问题。

我想查看我的数据库中的客户,所以我选择了一个基于ID的行。

这是我的模特:

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

这是我的控制器:

public function view($id)
{
    $this->load->model('Company_model');
    $data = $this->Company_model->view($id);
    $this->load->view('templates/header');
    $this->load->view('company/view', $data);
    $this->load->view('templates/footer');
}

以下是观点:

<?php echo $data('id'); ?>     

查看它,我得到:

  

消息:未定义的变量:id

任何帮助都会受到赞赏

4 个答案:

答案 0 :(得分:1)

在你的视图功能中给出类似

$data['data'] = $this->Company_model->view($id);

首先打印$ data并查看如何重新获取ID并在视图中将数据显示为

<?php echo $data['id']; ?>

它应该是“[]”而不是“()”,我认为你得到了所有记录数组,所以你需要使用循环来检索数据

答案 1 :(得分:0)

很可能是因为你在视图中拥有的东西。 $data不是一个功能,但你正在对它进行处理。当信息从控制器传递到视图时,它将作为方括号表示法的关联数组传递:

$data['id'];

答案 2 :(得分:0)

我认为当你使用

  

返回$ query-&gt; result();

你实际上是在发回一个对象而不是一个数组,这是@ChritopherW回答的补充。

答案 3 :(得分:0)

这里发生的是模型中的view()方法实际上是返回一个对象。

试试这个=]

型号:

public function view($id)
{
    /** $this->db->select(); for a 'SELECT *' you can omit this function call **/

    $query = $this->db->get_where('company', array('id' => $id), 1);

    return $query->row(); /* This returns the result object limited to the first row */
}

控制器:

public function view($id)
{
    $this->load->model('Company_model');

/** OK, two things are going on the next line of code, on the right side, we are selecting the 'id' parameter of the object returned by the view() method in the model
and we are applying that information to the $data[id] array, where the id hash in the array will become a public variable from the view's POV
**/
    $data[id] = $this->Company_model->view($id)->id;
    $this->load->view('templates/header');
    $this->load->view('company/view', $data);
    $this->load->view('templates/footer');
}

查看:

<!-- HTML CODE HERE -->
<?php

/* Remember the $data[id] in the controller? */
echo $id; 

?>