Methods of Query Builder Class In CodeIgniter 4 Tutorial

Reading Time: 6 minutes
12,530 Views

Inside this article we will see the concept of Methods of Query builder Class in CodeIgniter 4. It is way of interacting with database and perform database operations.

Other ways to query with database is –

  • Model based Database Operation
  • Using Raw Query

To get more idea about working with database, Click here.

Here, we will see Methods of Query Builder in CodeIgniter 4 for all CRUD operations.

Learn More –

  • MySQL Like Operator in CodeIgniter 4 Query Builder, Click here.
  • MySQL Group By in CodeIgniter 4 Query Builder, Click here.

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create table with some columns.

CREATE TABLE tbl_students (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Load Query Builder Instance

To use query builder in CodeIgniter 4 application, first we need to load that. Here is the simple way to load.

# Creating table instance

$builder = $this->db->table("tbl_students");

We have created a $builder an instance we can say to use Query builder methods. Right here passed tbl_students into table() method. You can load your table into it.

Next, we can call all methods like insert(), update(), delete() using $builder.


Create Controller

Open project into terminal and type this spark command.

$ php spark make:controller Student --suffix

It will create a file with name StudentController.php at /app/Controllers folder.

We will see all query builder CRUD methods by the help of this StudentController.php controller file.


Query Builder – Insert & Insert Batch Method

To insert data into table we have insert() and insertBatch() method available by this query builder $builder instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class StudentController extends BaseController
{
	public function __construct()
	{
		// Loading db instance
		$this->db = db_connect();
		// Loading Query builder instance
		$this->builder = $this->db->table("tbl_students");
	}

	public function insertData()
	{
		// Insert a single row
		$this->builder->insert([
			"name" => "Sanjay Kumar",
			"email" => "test@gmail.com",
			"mobile" => "9879638521"
		]);

		// Insert rows in bulk
		$this->builder->insertBatch([
			[
				"name" => "Sanjay Kumar",
				"email" => "test@gmail.com",
				"mobile" => "9879638521"
			],
			[
				"name" => "Ashish Kumar",
				"email" => "ashish@gmail.com",
				"mobile" => "6541231333"
			]
		]);
	}
}

Create Route

Open Routes.php from /app/Config folder.

//...

$routes->get("insert-student", "StudentController::insertData");

//...

URL: http://localhost:8080/insert-student


Query Builder – Update Method

To update data into table we have update() method available by this query builder $builder instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class StudentController extends BaseController
{
	public function __construct()
	{
		// Loading db instance
		$this->db = db_connect();
		// Loading Query builder instance
		$this->builder = $this->db->table("tbl_students");
	}

	public function updateData()
	{
		// Updated data
		$this->builder->set([
			"name" => "Sanjay Kumar",
			"email" => "test@gmail.com",
			"mobile" => "9879638521"
		]);
		// where condition
		$this->builder->where([
            "id" => 2
		]);
		// Calling update() method
		$this->builder->update();

		// OR
		// $this->builder->where([$condition])->set([$data])->update()
	}
}

Create Route

Open Routes.php from /app/Config folder.

//...

$routes->get("update-student", "StudentController::updateData");

//...

URL: http://localhost:8080/update-student


Query Builder – Delete Method

To delete data from table we have delete() method available by this query builder $builder instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class StudentController extends BaseController
{
	public function __construct()
	{
		// Loading db instance
		$this->db = db_connect();
		// Loading Query builder instance
		$this->builder = $this->db->table("tbl_students");
	}

	public function deleteData()
	{
		// where condition
		$this->builder->where([
            "id" => 2
		]);
		// Calling delete() method
		$this->builder->delete();

		// OR
		// $this->builder->where([$condition])->delete()
	}
}

Create Route

Open Routes.php from /app/Config folder.

//...

$routes->get("delete-student", "StudentController::deleteData");

//...

URL: http://localhost:8080/delete-student


Query Builder – Select Methods

To get data from table we have get() method available by this query builder $builder instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class StudentController extends BaseController
{
	public function __construct()
	{
		// Loading db instance
		$this->db = db_connect();
		// Loading Query builder instance
		$this->builder = $this->db->table("tbl_students");
	}

	public function selectData()
	{
		/****************/
		// Get all rows
		$all_students = $this->builder->get()->getResult();
		print_r($all_students);

		/****************/

		// Get single row
		$this->builder->where(array(
			"id" => 4
		));
		$single_student = $this->builder->get()->getRow();

		/****************/
	}
}

Create Route

Open Routes.php from /app/Config folder.

//...

$routes->get("get-student", "StudentController::selectData");

//...

URL: http://localhost:8080/get-student

To learn more about CodeIgniter 4 Model & Enity, Click here.

We hope this article helped you to learn about Methods of Query Builder In CodeIgniter 4 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more