Running Raw Queries in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 5 minutes
9,002 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.


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

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. Give your updated details of database connection string.

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

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5