Running Raw Queries in CodeIgniter 4 Tutorial

Reading Time: 5 minutes
14,103 Views

Inside this article we will see the concept of running raw queries. Raw query means running direct sql query of insert, update, delete etc commands.

Query execution in raw format probably is not a good approach. But in some cases where we need, you can use it. While using raw queries we also have the query binding concept which we can use as a type of placeholder for the values.

Query binding in CodeIgniter 4 includes the concept of placeholders for values and named binding.

This tutorial will provide you the complete concept of running raw queries in codeigniter 4.

Learn more –

  • Methods of Query Builder In CodeIgniter 4 Tutorial, Click here.
  • Working with Model in CodeIgniter 4 Tutorial, 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.


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.


Syntax for Raw Query Method

Use query() method of CodeIgniter 4.

$db = db_connect();

OR 

$db = \Config\Database::connect();

It will connect with default connection group of application. Now, by using $db we can write and run queries. You can write it into constructor method.

$db->query("<YOUR QUERY HERE>");

Raw Query – Insert Method

Need to use mysql insert query.

Syntax #1

$insertQuery = "INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, value3, ...)";

$db->query($insertQuery);

Example

$insertQuery = "INSERT INTO users (name, email, phone_no) VALUES ('Sanjay', 'sanjay@gmail.com', '2222222222')";

 if ($this->db->query($insertQuery)) {

        echo "DATA SAVED";
 }else{

        echo "FAILED TO SAVE DATA";
 }

Next, we will use the concept of Query Binding in CodeIgniter 4.

Syntax #2

$insertQuery = "INSERT INTO table_name (column1, column2, ...) VALUES (?, ?, ?, ...)";

$db->query($insertQuery, [value1, value2, value3, ...]);

Example

$insertQuery = "INSERT INTO users (name, email, phone_no) VALUES ( ?,  ? , ? )";

 if ($this->db->query($insertQuery, ['Sanjay', 'sanjay@gmail.com', '2222222222'])) {

        echo "DATA SAVED";
 }else{

        echo "FAILED TO SAVE DATA";
 }

Named Query Binding in CodeIgniter 4

Syntax #3

$insertQuery = "INSERT INTO table_name (column1, column2, ...) VALUES (:val1: , :val2: , :val3: , ...)";

$db->query($insertQuery, ["val1" => value1, "val2" => value2, "val3" => value3, ...]);

Example

$insertQuery = "INSERT INTO users (name, email, phone_no) VALUES ( :name:,  :email: , :mobile: )";

 if ($this->db->query($insertQuery, [
     "name" => 'Sanjay', 
     "email" =>  'sanjay@gmail.com', 
     "mobile" => '2222222222'
])) {

        echo "DATA SAVED";
 }else{

        echo "FAILED TO SAVE DATA";
 }

Here, we have seen the complete Idea of raw query of Insert operation. You can use the same concept with Select, Update, Delete.


Raw Query – Select Method

There are some select methods in CodeIgniter 4, which we need to use while adding select raw queries to get data.

$db->query("<YOUR QUERY HERE>");

Select Methods of CodeIgniter 4

We have few methods provided to fetch data.

  • getResult()
  • getResult(‘array’)
  • getResultArray()
  • getRow()

getResult() It returns data set into object form.

getResult(‘array’) & getResultArray() It returns data set into array form.

getRow() It returns a single specific row.

How to Use

$db->query("<YOUR SELECT QUERY HERE>")->getResult();

$db->query("<YOUR SELECT QUERY HERE>")->getResultArray();

$db->query("<YOUR SELECT QUERY HERE>")->getRow();

We hope this article helped you to learn about Running Raw Queries 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