Home > Net >  How to pass data from database to view in CodeIgniter
How to pass data from database to view in CodeIgniter

Time:04-21

I have a question about passing my data from model to view. Here is the code of my view named profile:

View :

<div >
<h2>Welcome <?php echo 'username'; ?>!</h2>
<a href="<?php echo base_url('login/logout'); ?>" >Logout</a>
<div >
    <h2>User information</h2>
    <p><b>Name: </b><?php echo $data['username']; ?></p>
    <p><b>Email: </b><?php echo $data['email']; ?></p>
    <p><b>Phone: </b><?php echo $data['phone']; ?></p>
    <p><b>Gender: </b><?php echo $data['gender']; ?></p>
</div>

controller:

here is the function profile() in the corresponding controller:

//show user information in profile after user log in
public function profile(){ 
    $this->load->model('user_model'); 
    $data = array(); 
    $this->load->view('template/header');
    if($this->session->userdata('logged_in')){ //check if user logged in

        $username = $this->session->userdata('username');//get username from session

        $data = $this->user_model->fetch($username);  //get the data according to the username
         
        // Pass the user data and load view  
        $this->load->view('profile', $data); 
     
    }else{ 
        redirect('login');
    }
    $this->load->view('template/footer');
} 

Model :

Here is the corresbonding function in model :

//fetch user data from database according to the username
public function fetch($username){
    $this->db->where('username', $username);
    $query = $this->db->get('users');
    return $query->row_array();
}

after user logged in, when I try to open the profile page, I see this error which reminded me that "data" in view is undefined var, could anyone know how to do with this bug ? the error

CodePudding user response:

$data is an array or an object.

Controller:-

$data = array(
    'title' => 'My Title',
    'heading' => 'My Heading',
    'message' => 'My Message'
);

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

View Page:-

<html>

<?php 
//Access them like so

echo $title;
echo $heading;
echo $message; 

?>

</html>

CodePudding user response:

i see you still use code format CodeIgniter3. CI4 have more simple Model like this:

class YourModel extends Model{

protected $table ='your_table';
protected $primaryKey = 'your_id';

protected $useAutoIncrement = true;

protected $returnType     = 'array';
protected $useSoftDeletes = false;

protected $allowedFields = [fieldA, fieldB, fieldC];

protected $useTimestamps = false;
protected $createdField  = 'created_at';
protected $updatedField  = 'updated_at';
protected $deletedField  = 'deleted_at';

protected $validationRules    = [];
protected $validationMessages = [];
protected $skipValidation     = false;

}

And, If you want to select data. You can call model on your controller:

public function getData()
{
    $urMdl= new YourModel();

    $data['urData']= $urMdl->findAll();
    echo view('your_view', $data);


}
  • Related