How to fetch data from a table in CodeIgniter?

This code explains how to fetch data from a table in CodeIgniter.
This process majorly contains three steps


  1. Model
  2. Controller
  3. View
Once you aware of setting up the database you can move ahead with this example.


Model
Fetching data from database table.
Levels.php
<?php
class Levels extends CI_Model {
public function selectdemodata()
    {
$this->load->database();
$query = $this->db->get('demo');
return $query;
    }
}
?>


Controller
Storing the data in an array.
Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller
{
public function demodata()
    {
$data_demo['k'] = $this->levels->selectdemodata();
$this->load->view('demodata', $data_demo);
    }
}
?>


View
Displaying data in a table.
demodata.php
<html>
<head>
<style>
        .container {
width: 500px;
height: 100px;
padding: 200px;
        }
table, th, td {
border: 1px solid black;
width:300px;
        }
</style>
</head>
<body class="container">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Number</th>
</tr>

<?php
    foreach ($k->result() as $row) {
echo '<tr>';
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>' . $row->number . '</td>';
    }
?>

</table>
</body>
</html>

Result:

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts