PHP MVC CodeIgniter Laravel Core PHP MORE

How to View data in database using PHP MVC with example


In this example we using Models, Views, Controller Structure for View the inserted data.

To View data in the database first we have to create a Controller file.

controller/index.php

<?php

class Index extends Controller {

	function __construct() {
		parent::__construct();
	}
	
	function index() {
	
		$this->view->allrecords = $this->model->getAllrecords();
		$this->view->render('index/index');
		
	}
	function view_index() 
	{
	/* Auth::handleLogin(); */
		$data = $_GET;
		if($data['id']=='')
		    {
				$this->view->pick='';
				$this->view->data=$data;
			} 
		else 
			{
				$this->view->pick=$data['id'];
				$this->view->content= $this->model->viewOnerecord($data['id']);
							}

	$this->view->render('index/view_index');
	}
	}
	

Here is the model file which we are using for View data from database.

The file index_model.php is created under Models folder

models/index_model.php

index_model.php

<?php

class Index_Model extends Model
{
	public function __construct()
	{
		parent::__construct();
	}

	public function getAllrecords()
	{
		return $this->db->select("SELECT * FROM `mvc` ORDER BY id DESC");
	}
	public function viewOnerecord($id)
	{
		return $this->db->select("SELECT * FROM `mvc` WHERE id='".$id."' LIMIT 1");
	}
	

Here is the view file index.php which inside views folder contains the table

views/index/index.php

<table border="2" id="internalActivities" style="width:100%" class="table table-bordered">
    <tbody>
      <tr>
		<th>id</th>
			<td><?php echo $this->content[0]['id']; ?></td>
		<th>name</th>
			<td><?php echo $this->content[0]['name']; ?></td>
	  </tr>
	  <tr>
		<th>email</th>
			<td><?php echo $this->content[0]['email']; ?></td>
		<th>contact</th>
			<td><?php echo $this->content[0]['contact']; ?></td>
	  </tr>	
    </tbody>
</table>

Path: localhost/project_folder_name/view_folder_name/view_filename
Example: localhost/mvc/index/index