Methods of Query Builder Class In CodeIgniter 4 Tutorial

Share this Article
Reading Time: 7 minutes
4,806 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.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

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 database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with 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.

//.. Other routes

$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.

//.. Other routes

$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.

//.. Other routes

$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.

//.. Other routes

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

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

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

Learn More –

  • Running Raw Queries in CodeIgniter 4 Tutorial, Click here.

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

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.

Find More on CodeIgniter 4 here