Home >>Codeigniter Tutorial >Codeigniter display data from database

Codeigniter display data from database

Codeigniter display data from database

In this tutorial, we will understand how to display(fetch) data from database and display records in view. In the Previous example we saved records inside users table.
In this example We will use users table to display records.

Controller

Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller 
{
	public function __construct()
	{
	parent::__construct();
	$this->load->database();
	$this->load->helper('url');
	$this->load->model('Hello_Model');
	}

	public function savedata()
	{
		$this->load->view('registration');
		if($this->input->post('save'))
		{
		$n=$this->input->post('name');
		$e=$this->input->post('email');
		$m=$this->input->post('mobile');
		$this->Hello_Model->saverecords($n,$e,$m);		
		redirect("Hello/dispdata");  
		}
	}
	
	public function dispdata()
	{
	$result['data']=$this->Hello_Model->displayrecords();
	$this->load->view('display_records',$result);
	}
}
?>

View

Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
  <tr style="background:#CCC">
    <th>Sr No</th>
    <th>Name</th>
    <th>Email</th>
    <th>Mobile</th>
  </tr>
  <?php
  $i=1;
  foreach($data as $row)
  {
  echo "<tr>";
  echo "<td>".$i."</td>";
  echo "<td>".$row->name."</td>";
  echo "<td>".$row->email."</td>";
  echo "<td>".$row->mobile."</td>";
  echo "</tr>";
  $i++;
  }
   ?>
</table>

</body>
</html>

Model

Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model 
{
	function saverecords($name,$email,$mobile)
	{
	$query="insert into users values('','$name','$email','$mobile')";
	$this->db->query($query);
	}
	
	function displayrecords()
	{
	$query=$this->db->query("select * from users");
	return $query->result();
	}
}

Calling/run Hello Controller’s dispdata method

Open your web browser and Pass : http://localhost/CodeIgniter/index.php/Hello/dispdata


No Sidebar ads