简体   繁体   中英

How to pass data controller to view in codeigniter

I am getting user profile fields from the database and want to display in my view but don't know to do this with the master layout.

this is my model

function fetchProfile($id,$page){
 $query = $this->db->query("SELECT * FROM staff_master WHERE Id='$id'");
 return $query->result(); 
}

this is my controller:

public function edit($id,$page){
    $data['query'] =  $this->StaffModel->fetchProfile($id,$page);
    $data= array('content'=>'view_staff_edit');
    $this->load->view('template_master',$data);
}

I am also trying to find a solution. I am passing user Id and another by URL (get method).

You are overwriting $data['query'] when you assign the array next:

$data['query'] =  $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');

Either do:

$data= array('content'=>'view_staff_edit');
$data['query'] =  $this->StaffModel->fetchProfile($id,$page); // note position

Or:

$data = array(
    'content' = 'view_staff_edit',
    'query' => $this->StaffModel->fetchProfile($id,$page),
);

Access in view via $query and $content .

Unrelated:

You are also missing $page in your query, and its generally a good idea to declare gets as null if not set or you will get a notice: public function edit($id=null,$page=null){

Your overriding your first declaration of variable $data what you can do is to initialize them both at the same time.

Controller

public function edit($id,$page){
    $data = array(
        'query'   => $this->StaffModel->fetchProfile($id,$page),
        'content' => 'view_staff_edit'
    );
    $this->load->view('template_master',$data);
}

Then access it on your View file

<h1><?php echo $content ?></h1>

<?php foreach($query as $result): ?>

    <p><?php echo $result->id ?></p>

<?php endforeach; ?>

Try doing something like this:

public function edit($id,$page) {

    $data['query'] =  $this->StaffModel->fetchProfile($id,$page);
    $data['content']= 'view_staff_edit';
    $this->load->view('template_master',$data);

}

YOUR MODEL

function fetchProfile($id){
    return $this->db->get_where('Id' => $id)->result_array(); 
}

YOUR CONTROLLER

public function edit($id,$page){
$data = array(
    'query'   => $this->StaffModel->fetchProfile($id),
    'content' => 'view_staff_edit',   
);
$this->load->view('template_master',$data);
}

YOUR "template_master" VIEW

<?php foreach ($query as $res){?>
<span><?php echo $res['Id'];?></span> //User html content according to your requirements ALSO you can add all columns retrieved from database
<?php } ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM