How To Import CSV Data in MySQL Database CodeIgniter 4

Reading Time: 6 minutes
6,981 Views

Inside this article we will see the concept i.e How To Import CSV Data in MySQL Database CodeIgniter 4. Article contains the classified information about Codeigniter 4 Import CSV Data to MySQL Database Tutorial.

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.

Learn More –

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.

Now, let’s configure database and application connectivity.

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.

Create Database Table

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 table. Let’s connect with the application.

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.

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.

Application Controller Settings

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.

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

<?php

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],
                        );
                    }
                    $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

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

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

<head>
    <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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.2/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        #frm-add-students label.error {
            color: red;
        }
    </style>
</head>

<body>

    <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">
                <?php
                if (session()->get("success")) {
                ?>
                    <div class="alert alert-success">
                        <?= session()->get("success") ?>
                    </div>
                <?php
                }
                ?>
                <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>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>

</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Validation library file -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<!-- Sweetalert library file -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.2/dist/sweetalert2.min.js"></script>

<script>
    $(function() {

        // Adding form validation
        $('#frm-add-students').validate();
    });
</script>
  • 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 learn about How To Import CSV Data in MySQL Database CodeIgniter 4 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.