Import CSV File Data into MySQL Database CodeIgniter 4

Share this Article
Reading Time: 6 minutes

Uploading data from file like from CSV, Excel is a common function at admin panel. When we need to upload huge amount of data then we need this file import functionality.

Inside this article we will see Import CSV File Data into MySQL Database CodeIgniter 4.

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.

Now, let’s configure database and application connectivity.

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 table with some columns.

CREATE TABLE tbl_students (
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    designation varchar(100) DEFAULT NULL,
    PRIMARY KEY (id)

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

Create Route

Open Routes.php from /app/Config folder. Add this route into it.


$routes->match(["get", "post"], "upload-student", "Student::uploadStudent");

To remove /public/index.php from URL, you can find it’s complete resource here at this link.

Let’s create Controller.

Application Controller Settings

Next we need to create application controller.

Loading url Helper

Open BaseController.php from /app/Controllers folder. Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = [‘url’];

This url helper will load base_url() and site_url() functions.

Also we have the option to load any helper directly to any controller using helper() function.

$ php spark make:controller Student

It will creates Student.php file at /app/Controllers folder.

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


namespace App\Controllers;

class Student extends BaseController
    public $db;

    public function __construct()
        $this->db = \Config\Database::connect();
        // $this->db = db_connect();

    public function uploadStudent()
        if ($this->request->getMethod() == "post") {

            $file = $this->request->getFile("file");

            $file_name = $file->getTempName();

            $student = array();

            $csv_data = array_map('str_getcsv', file($file_name));

            if (count($csv_data) > 0) {

                $index = 0;

                foreach ($csv_data as $data) {

                    if ($index > 0) {

                        $student[] = array(
                            "name" => $data[1],
                            "email" => $data[2],
                            "mobile" => $data[3],
                            "designation" => $data[4],

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


                $session = session();

                $session->setFlashdata("success", "Data saved successfully");

                return redirect()->to(base_url('upload-student'));

        return view("upload-file");
  • if ($this->request->getMethod() == “post”) Checking request type
  • $this->db = \Config\Database::connect(); Initializing database instance
  • $file = $this->request->getFile(“file”); Read file from posted data
  • $csv_data = array_map(‘str_getcsv’, file($file_name)); Reading CSV data and converting into array format.
  • $builder = $this->db->table(‘tbl_students’); Creating a builder object
  • $builder->insertBatch($student); Saving student bulk data once into database table.
  • $session = session(); Creating a session instance for flashdata.

View File Settings

Create upload-file.php inside /app/Views folder. Open file and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

    <title>Import CSV File Data into MySQL Database CodeIgniter 4</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <link href="" rel="stylesheet" />
        #frm-add-students label.error {
            color: red;


    <div class="container">
        <h4 style="text-align: center;">Import CSV File Data into MySQL Database CodeIgniter 4</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Import CSV File Data into MySQL Database CodeIgniter 4</div>
            <div class="panel-body">
                if (session()->get("success")) {
                    <div class="alert alert-success">
                        <?= session()->get("success") ?>
                <form class="form-horizontal" enctype="multipart/form-data" method="post" action="<?= site_url('upload-student') ?>" id="frm-add-students">
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="file">File:</label>
                        <div class="col-sm-10">
                            <input type="file" class="form-control" required id="file" placeholder="Enter file" name="file">
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary">Submit</button>



<script src=""></script>
<!-- Validation library file -->
<script src=""></script>
<!-- Sweetalert library file -->
<script src=""></script>

    $(function() {

        // Adding form validation
  • Creating a view file with input type file button.
  • session()->get(“success”) It is for outputting session flash data.

Application Testing

Open project into terminal and start development server.

$ php spark serve

URL – http://localhost:8080/upload-student

Submit form without any file

Upload data to be in csv format

We hope this article helped you to import CSV data into MySQL database in CodeIgniter 4 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