Working with MySQL Inner Join in CodeIgniter 4

Share this Article
Reading Time: 6 minutes
861 Views

When we work with MySQL Queries, then definitely for some relational data we need to work with Joins. Inside this article we will see the concept of Inner Join in CodeIgniter 4.

Joins in CodeIgniter 4 is the connection between one and more tables to get data. In MySQL we have Inner join, Left join, Right join, Outer join.

We will see the concept of Inner Join in this CodeIgniter 4 article.

Learn More –

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.


Types of Joins available in CodeIgniter 4

In CodeIgniter 4 application, as per the documentation we have 3 types of joins available. Here are the followings –

  • Inner Join
  • Left Join
  • Right Join

What is Inner Join?

Inner Join – This join brings the data on the basis of a common value condition between two or more than two tables. According to matched condition it will bring all data what we expected for. It remove those rows from result set which has no matched condition.

How can we use inside an application and get relational data we will see by making an application. Let’s create an application in which we use Inner Join.


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

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

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create two tables with some columns.

CREATE TABLE `tbl_users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `phone_no` varchar(120) DEFAULT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `tbl_courses` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) NOT NULL,
 `user_id` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Table courses contains user_id column on the basis of which we are going to make use of join. Successfully, we have created a database and two tables.

Let’s insert some dummy data into these tables.


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.


Creating Test data for Application

Here we have some sql queries, you need to copy and run into database. It will inserts data into tables.

Test data for tbl_users

--
-- Dumping data for table `tbl_users`
--
  
INSERT INTO `tbl_users` (`id`, `name`, `email`, `phone_no`, `created_at`) VALUES
(1, 'Sanjay', 'sanjay@gmail.com', '8527419630', '2020-09-10 13:19:38'),
(2, 'Vijay', 'vijay@gmail.com', '9875643125', '2020-09-25 11:33:00'),
(3, 'Ashish Kumar', 'ashish@gmail.com', '7896541230', '2020-09-25 11:33:17');

Test data for tbl_courses –

--
-- Dumping data for table `tbl_courses`
--

INSERT INTO `tbl_courses` (`id`, `name`, `user_id`) VALUES
(1, 'Learn CodeIgniter 4', 1),
(2, 'Learn PHP', 2),
(3, 'Learn CakePHP 4', 30),
(4, 'Learn Laravel', 35);

To Learn about Seeders in CodeIgniter 4, Click here.


Create Routes

Open Routes.php from /app/Config. Add these routes into this file.

//..

$routes->get('inner-join', 'Site::innerJoinMethod');

Let’s create Controller.


Create Controller

Open project into terminal and run this spark command to create controller.

$ php spark make:controller Site

It will create Site.php at /app/Controllers folder.

Open Site.php and write this complete code into it.

<?php

namespace App\Controllers;

class Site extends BaseController
{
    private $db;

    public function __construct()
    {
        $this->db = db_connect(); // Loading database
        // OR $this->db = \Config\Database::connect();
    }

    public function innerJoinMethod()
    {
        $builder = $this->db->table("tbl_users as user");
        $builder->select('user.*, course.name as course_name');
        $builder->join('tbl_courses as course', 'user.id = course.user_id');
        $data = $builder->get()->getResult();

        echo "<pre>";
        print_r($data);
      
        // To print query
        // $this->db->getLastQuery();
    }

    //...
}

Behind the scene executed query is –

SELECT `user`.*, `course`.`name` as `course_name` FROM `tbl_users` as `user` JOIN `tbl_courses` as `course` ON `user`.`id` = `course`.`user_id`

Application Testing

Start development server:

$ php spark serve

URL – http://localhost:8080/inner-join

Have a look output –

We are getting only matched rows according to the condition user.id = course.user_id

We hope this article helped you to learn MySQL Inner join in codeigniter 4 in a very detailed way.

Buy Me a Coffee

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