-1

Controller: I'm trying to fetch the records from database, but it is showing undefined variable $data in the view section. What is the problem i don't understand.

public function vabout(){
    if(!$this->session->userdata('logged_in')){
        redirect('register/login');
    }
    $this->load->model('profile_model');
    $data = $this->profile_model->viewprofile();

    $this->load->view('templates/pheader');
    $this->load->view('profile/viewabout',$data);
    $this->load->view('templates/pfooter');

}

Model: This is the model section, is there any issue in model for fetching the record?

public function viewprofile(){
    $data = $this->db->get('profile');
    return $data->row_array();
}

View: errore: a php error encountered $data is undefined

<?php
      foreach ($data as $row)
        { ?>
        <p><?php echo $row->id; ?></p>
        <p><?php echo $row->name; ?></p>
        <?php
      }
  ?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

2 Answers2

1

You need to pass array with key name $datanot contain data as key name, Every key you pass with data array will become variable in view

public function vabout(){
                if(!$this->session->userdata('logged_in')){
                    redirect('register/login');
                }
                $this->load->model('profile_model');
                $data['data'] = $this->profile_model->viewprofile(); // add data as index

                $this->load->view('templates/pheader');
                $this->load->view('profile/viewabout',$data);
                $this->load->view('templates/pfooter');

            }

Also you are retrieving data in view like object. So in model not convert result in array

public function viewprofile(){
    $data = $this->db->get('profile');
    return $data->result();
}
B. Desai
  • 16,414
  • 5
  • 26
  • 47
1

Replace your code with this: Controller

 public function vabout($id = NULL){
        if(!$this->session->userdata('logged_in')){
            redirect('register/login');
        }
        $this->load->model('profile_model');
        $data['data'] = $this->profile_model->viewprofile($id);

        $this->load->view('templates/pheader');
        $this->load->view('profile/viewabout',$data);
        $this->load->view('templates/pfooter');

    }

Replacing model with this. Is it right then?

Model:

public function viewprofile($id = FALSE){
     if($id === FALSE){
        $query = $this->db->get('profile');
        return $query->result_array();
      }
         $query = $this->db->get_where('profile',array('id' => $id);
         return $query->row_array();
    }

View:

<?php
              foreach ($data as $row)
                { ?>
                <p><?php echo $row['id']; ?></p>
                <p><?php echo $row['name']; ?></p>
                <?php
              }
          ?>
flixy
  • 73
  • 2
  • 10