Codeigniter Display Data From Database - A Beginner's Guide
In this example we are going to show you how to display data from database using CodeIgniter framework in PHP.
Contents
- Download Codeigniter 3
- Create a new Database
- Create a new table
- Create a new project name
- Create a new controller file
- Create a new model file
- Create a new view file
The Display statement is used to display records from a table:
Following Steps:
- Create a new table in Mysql database
- Project folder name is codeIgniter
- Database name is sample
- Create new controller file in Path: codeIgniter\application\controllers\Home.php
- Create new view file in Path: codeIgniter\application\views\list_data.php
- Create new model file in Path: codeIgniter\application\models\Home_model.php
1. For creating table the SQL query is:
CREATE TABLE crud (`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,`first_name` varchar(30) NOT NULL,`last_name` varchar(30) NOT NULL,`email` varchar(30) NOT NULL,`mobile` varchar(30) NOT NULL);
2. Home.php (Controller)
<?phpclass Home extends CI_Controller{public function __construct(){/*call CodeIgniter's default Constructor*/parent::__construct();/*load database libray manually*/$this->load->database();/*load Model*/$this->load->model('Home_model');}/*Display data*/public function list_data(){$result['data'] = $this->Home_model->display_records();$this->load->view('display_records', $result);}}?>
3. list_data.php (View)
<!DOCTYPE html><html><head><title>Display Data</title></head><body><table width="600" border="1" cellspacing="5" cellpadding="5"><tr style="background:#CCC"><th>Sr No</th><th>First_name</th><th>Last_name</th><th>Email Id</th><th>Mobile</th></tr><?php$i = 1;foreach ($data as $row) {echo "<tr>";echo "<td>" . $i . "</td>";echo "<td>" . $row->first_name . "</td>";echo "<td>" . $row->last_name . "</td>";echo "<td>" . $row->email . "</td>";echo "<td>" . $row->mobile . "</td>";$i++;}?></table></body></html>
4. Home_model.php (Model)
<?phpclass Home_model extends CI_Model{/*Display*/public function display_records(){$query = $this->db->get("crud");return $query->result();}}?>
Finally enter this url in your browser : http://localhost/codeIgniter/index.php/home/list_data
We hope this guide has been helpful. If you have any questions or need further assistance, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
0 Comments