1

I would like to use the $data['main'] and get a specific row or data from it which is: extra_id

I would use extra_id for another function.

I tried accessing the data from the $data['main'] just like what I did on the view of the other page which is: $extra_id = $main->result()->extra_id;

Unfortunately, it did not work.

controller:

public function viewData($id)
    {   

    $this->load->model('myModel');

    $data['main'] = $this->MyModel->getMainData($id);

    $extra_id = $main->result()->extra_id; //error here. undefined variable main.

    $data['extra'] = $this->MyModel->getExtraData($extra_id);



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

model:

public function getMainData($id) {
        $this->db->select('main.id as extra_id');
        $this->db->select('main.*');
        $this->db->select('extra.*');

        $this->db->from('main');

        $this->db->join('extra', 'extra.main_id = main.id');

        $query = $this->db->get();  
        return $query;
}
guwop69
  • 119
  • 1
  • 13

3 Answers3

1

You initialize $data['main'] and then use $main....it doesn't work that way. Try this:

$extra_id = $data['main']->result()->extra_id;

My guess is the place you copied that bit of code from, you assigned it to a variable called $main in that method.

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0

Did you try like this...

In codeiginter the result() extract more than one rows on object form and function row() is used to obtain only first row in object form.

Controller:

public function viewData($id)
    {   

    $this->load->model('myModel');

    $data['main'] = $this->MyModel->getMainData($id);

    $extra_id = $data['main']->extra_id; //error here. undefined variable main.

    $data['extra'] = $this->MyModel->getExtraData($extra_id);


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

Model:

public function getMainData($id) {
        $this->db->select('main.id as extra_id');
        $this->db->select('main.*');
        $this->db->select('extra.*');

        $this->db->from('main');

        $this->db->join('extra', 'extra.main_id = main.id');

        $query = $this->db->get()->row();  
        return $query;
}
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
0

Use this code.

$extra_id = $data['main']->result()[0]->extra_id;

And Use $id in where clause in model.

 $this->db->where("id",$id);
Niklesh_Chauhan
  • 647
  • 5
  • 16