Pages

Friday, February 2, 2018

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:

Featured

Simple User Registration Form Using PHP, MySQL