As you all are know codeigniter is an MVC framework, now by using model, view and controller we will retrieve data from mysql table and display in codeigniter view.
I had taken a small table with firstname, lastname and emailed. Now I will create a controller function. Here from below diagram you will get an overview how Model, view and controller works.
Now create controller file under applications/controller/welcome.php ,open the controller file copy
below code there.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends CI_Controller { public $data; public function __construct() {//Core controller constructor parent::__construct(); $this->load->model('ektreemodel'); } public function fetchdata() { $data['fetchdata']=$this->ektreemodel->get_users(); $this->load->view('fetchangulardata',$data); } } ?>
Now let’s check model file, create file under applications/model/ektreemodel.php.
Open the file and copy below code in the model file.
<?php class Ektreemodel extends CI_Model { public function get_users() { $this->db->select('*'); $this->db->from('registration'); $query = $this->db->get(); return $query; } } ?>
Now finally create a view under applications/views/fetchdata.php,Open the file and copy the below code in view.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> How to retrieve data from mysql and display in codeigniter view? </title> <link rel="stylesheet" href="<?php echo base_url();?>/css/bootstrap.min.css"> <link rel="stylesheet" href="<?php echo base_url();?>/css/bootstrap-theme.min.css"> <script src="<?php echo base_url();?>scripts/jquery-2.0.0.min.js"></script> <script src="<?php echo base_url();?>scripts/bootstrap.min.js"></script> </head> <body > <div> <input type="text" class="form-control"> <table class="table table-hover"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email Id</th> </tr> </thead> <tbody> <?php foreach($fetchdata->result() as $row) { ?> <tr> <td><?php echo $row->firstname;?></td> <td><?php echo $row->lastname;?></td> <td><?php echo $row->emailid;?></td> </tr> <?php } ?> </tbody> </table> </div> </body> </html>
Now finally open the xampp and start apache and mysql servers. And then go to browser and type localhost:/projectname/index.php/controller_name/function_name
Example: localhost:/codeigniter/index.php/welcome/fetchdata
Now you will get output as below…
Thanks for reading this article ,feel free to post your comments below for any issues.
Excellent!