For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Retrieve data from Database using CodeIgniter 4

Overview

Here, we are using 3 files for retrieve data from MySQL:

Controller: 	User.php		/app/Controllers/User.php
Model:		UserModel.php		/app/Models/UserModel.php
View:		list.php		/app/Views/list.php

/app/Config/Routes.php

$routes->add('user/list', 'User::list');

/app/Controllers/User.php

<?php
namespace App\Controllers;

use App\Models\UserModel;

class User extends BaseController {

	public function __construct() {

		$db = db_connect();
		$this->userModel = new UserModel($db);
	}

	public function add() {
		$this->load->view('add');
	}

	public function list() {
		$data['result']	= $this->userModel->list();
		echo view('list', $data);
	}
}

/app/Models/UserModel.php

<?php 
namespace App\Models;

use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;

class UserModel extends Model {
	
	protected $db;
	public function __construct(ConnectionInterface &$db) {
		$this->db =& $db;
	}

	public function list() {
		return $this->db
                        ->table('user_info')
                        ->get()
                        ->getResult();
	}
	
}

/app/Views/list.php

<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>
	</tr>
	<?php $i=1; foreach($result 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 "</tr>"; $i++; } ?>
</table>