Avg Data from Database in CodeIgniter 4 Model and Entity

Create new database named codeigniter4_db. This database have 1 table: Product table.

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` double NOT NULL,
  `quantity` int(11) NOT NULL,
  `status` tinyint(1) NOT NULL,
  `created` date NOT NULL,
  `description` text NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `created`, `description`, `category_id`) VALUES
('Tivi 1', 20, 4, 1, '2021-07-13', 'good', 1),
('Tivi 2', 63, 15, 0, '2020-08-11', 'good', 1),
('Laptop 1', 24, 12, 1, '2021-08-12', 'good', 2),
('Laptop 2', 60, 34, 1, '2020-08-12', 'good', 2),
('Laptop 3', 23, 27, 0, '2020-08-17', 'good', 3),
('Computer 1', 4.5, 2, 1, '2021-08-20', 'ABC', 3),
('Computer 2', 111, 222, 1, '2021-09-25', 'AAA', 7),
('Computer 3', 33333, 888, 0, '2021-10-11', 'abc', 2),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7);

Download the latest version of CodeIgniter 4 and unzip source code to new folder named LearnCodeIgniter4WithRealApps

Cut index.php and htaccess files in public folder to root folder of project

Open index.php in root folder find to line 16 replace path to Paths.php file as below:

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

Open App.php in app/Config folder find to line 39 remove index.php string in $indexPage variable as below:

public $indexPage = '';

Open App.php file in app/Config folder. Set value for $baseURL variable as below:

public $baseURL = 'http://localhost:8091/LearnCodeIgniter4WithRealApps/';

Open Database.php file in app/Config folder and add values as below connect to database:

<?php

public $default = [
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'codeigniter4_db',
	'port'     => 3306,
];

Create new PHP file named ProductModel.php in app/Models folder as below:

<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
	protected $table      = 'product';

	protected $primaryKey = 'id';

	protected $returnType = 'array';

	protected $allowedFields = ['name', 'price', 'quantity', 'status', 'created', 'description'];
}				
			

Create new PHP file named Demo.php in app/Controllers folder as below:

<?php

namespace App\Controllers;

use App\Models\ProductModel;

class Demo extends BaseController
{
	public function demo1()
	{
		$productModel = new ProductModel();
		$result = $productModel->select('avg(price) as avgPrice')->first();
		$data['avg'] = $result['avgPrice'];
		return view('demo/index', $data);
	}

	public function demo2()
	{
		$productModel = new ProductModel();
		$result = $productModel->where('status', 0)->select('avg(price) as avgPrice')->first();
		$data['avg'] = $result['avgPrice'];
		return view('demo/index', $data);
	}

}											

Create new folder named demo in app/Views folder. In this folder, create new PHP file named index.php as below:

<html>

	<head>
		<title>Modeling Data and ORM in CodeIgniter 4</title>
	</head>

	<body>

		Avg: <?= $avg ?>

	</body>

</html>

Open Routes.php file in app/Config folder. Set default controller as below:

$routes->get('/', 'Demo::demo1');
$routes->get('/demo', 'Demo::demo1');
$routes->get('/demo/demo1', 'Demo::demo1');
$routes->get('/demo/demo2', 'Demo::demo2');

Access demo1 action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/demo1

Output

Avg: 34.4375

Access demo2 action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/demo2

Output

Avg: 33.33