Import CSV File Data into MySQL Database CodeIgniter 4

Share this Article

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.


Settings Environment Variables

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,
    designation varchar(100) 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.


Create Route

To configure application routes, we need to open up the file Routes.php from /app/Config. This is the main routes config file where we will do all routes of application.

//.. Other routes

$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

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create Student.php inside the given folder. Open project into terminal and run this spark command.

$ php spark make:controller Student

Write the following code into /app/Controllers/Student.php

<?php

namespace App\Controllers;

class Student extends BaseController
{
    public $db;

    public function __construct()
    {
        $this->db = \Config\Database::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],
                        );
                    }
                    $index++;
                }

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

                $builder->insertBatch($student);

                $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

View file will be created at /app/Views/upload-file.php

<?php
  if(session()->get("success")){
      
    echo session()->get("success");
  }
?>

<form method="post" action="<?php echo site_url('upload-student') ?>" enctype="multipart/form-data">

    <p>
        Choose file: <input type="file" name="file" required/>
    </p>

    <p>
        <button type="submit">Submit</button>
    </p>

</form>
  • 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

First, let’s prepare a data sheet CSV file for students record.

Back to browser and type the URL – http://localhost:8080/upload-student

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

Leave a Comment