Codeigniter 4 Import CSV File Data To MySQL Database Example

Apr 20, 2022 . Admin



Hi Dev,

In this article we will cover how to implement codeigniter 4 import csv or excel file to database. you will learn Codeigniter 4 to import data from csv or excel file. step by step explain import csv or excel file Codeigniter 4. I’m going to show you about import csv or excel file in PHP Codeigniter 4. Let's see below example import csv Codeigniter 4.

Today I will be explaining How to Import CSV File Data To MySQL Database in Codeigniter 4. This example is so easy to use in Codeigniter 4.

We will share specific instructions that will help you quench your first to create a simple functionality to import CSV files to MySQL database Codeigniter.

So let's start to the example.

Step 1: Install Codeigniter 4

First of all if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2: Configure Error Handling

Next step we can use error handling, set display_errors to 1 in app/Config/Boot/production.php, it makes the error handling process profoundly facile.

ini_set('display_errors', '1');
Step 3: Generate User Table in Database

In this step to generate a database table in your application database.

CREATE TABLE students (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(150) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email',
    phone varchar(250) NOT NULL COMMENT 'Phone',
    created_at varchar(20) NOT NULL COMMENT 'Date Created',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Student table' AUTO_INCREMENT=1;
Step 4: Connect To Database

So, in this step open your app/Config/Database.php, and insert database name, username and password into the file.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'codeigniter_db',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'development'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
    ];
Step 5: Create Sample CSV File

Here if you want a CSV file, you can copy the following comma-separated code, paste it into the code editor and save the file with the .csv extension.

name, email, phone, created_at
Sam Coury, christine1998@yahoo.com, 772-267-3636, 2021-02-02
Chris Ellis, ellis@yahoo.com, 270-562-2304, 2020-03-03
Cameron Finley, cameron@rediff.com, 813-416-4979, 2019-01-05
Howard Schlueter, schlueter@gmail.com, 828-207-1592, 2018-05-02
Jordan Tafoya, annabell2001@hotmail.com, 512-596-3622, 2017-05-11
Step 6: Create Model

Then next step to create a StudentModel model in your CodeIgniter application.

app/Models/StudentModel.php
<?php 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class StudentModel extends Model
{
    protected $table = 'students';
    protected $allowedFields = [
        'name', 
        'email', 
        'phone',
        'created_at'
    ];
}
Step 7: Set Up Controller

pCreate StudentController.php file in the app/Controllers directory, then insert the below code into the file.

app/Controllers/StudentController.php
<?php 
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use App\Models\StudentModel;

class StudentController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('index');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function importCsvToDb()
    {
        $input = $this->validate([
            'file' => 'uploaded[file]|max_size[file,2048]|ext_in[file,csv],'
        ]);

        if (!$input) {
            $data['validation'] = $this->validator;
            return view('index', $data); 
        }else{
            if($file = $this->request->getFile('file')) {
                if ($file->isValid() && ! $file->hasMoved()) {
                    $newName = $file->getRandomName();
                    $file->move('../public/csvfile', $newName);
                    $file = fopen("../public/csvfile/".$newName,"r");
                    $i = 0;
                    $numberOfFields = 4;

                    $csvArr = array();
                    
                    while (($filedata = fgetcsv($file, 1000, ",")) !== FALSE) {
                        $num = count($filedata);
                        if($i > 0 && $num == $numberOfFields){ 
                            $csvArr[$i]['name'] = $filedata[0];
                            $csvArr[$i]['email'] = $filedata[1];
                            $csvArr[$i]['phone'] = $filedata[2];
                            $csvArr[$i]['created_at'] = $filedata[3];
                        }
                        $i++;
                    }
                    fclose($file);

                    $count = 0;
                    foreach($csvArr as $userdata){

                        $students = new StudentModel();
                        $findRecord = $students->where('email', $userdata['email'])->countAllResults();

                        if($findRecord == 0){
                            if($students->insert($userdata)){
                                $count++;
                            }
                        }
                    }
                    session()->setFlashdata('message', $count.' rows successfully added.');
                    session()->setFlashdata('alert-class', 'alert-success');
                }else{
                    session()->setFlashdata('message', 'CSV file coud not be imported.');
                    session()->setFlashdata('alert-class', 'alert-danger');
                }
            }else{
                session()->setFlashdata('message', 'CSV file coud not be imported.');
                session()->setFlashdata('alert-class', 'alert-danger');
            }
        }
        return redirect()->route('/');         
    }
}
Step 8: Set Up Routes app/Config/Routes.php
$routes->get('/', 'StudentController::index');
$routes->post('import-csv', 'StudentController::importCsvToDb');
Step 9: Create Codeigniter View File

Next to create a view file in your application/View under directiory:

app/View/index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="The tiny framework with powerful features">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Codeigniter 4 Import CSV File Data To MySQL Database Tutorial - Mywebtuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 500px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header text-center">
                <strong>Upload CSV File</strong>
            </div>
            <div class="card-body">
                <div class="mt-2">
                    <?php if (session()->has('message')){ ?>
                        <div class="alert <?=session()->getFlashdata('alert-class') ?>">
                            <?=session()->getFlashdata('message') ?>
                        </div>
                    <?php } ?>

                    <?php $validation = \Config\Services::validation(); ?>
                </div>  
                <form action="<?=site_url('import-csv') ?>" method="post" enctype="multipart/form-data">
                    <div class="form-group mb-3">
                        <div class="mb-3">
                            <input type="file" name="file" class="form-control" id="file">
                        </div>                     
                    </div>
                    <div class="d-grid">
                        <input type="submit" name="submit" value="Upload" class="btn btn-dark" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
Step 10 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/
Output

Now you can check your own.

I hope it can help you...

#Codeigniter 4