TECHNICALSTUDY

The associate of technical study article for computer science students which could gain the knowledge about to technicals like Computer history, hard disk, printer,central processing unit etc. Technicalstudy also considered software engineering, operating system and some chunks of programming languages.

Email subscription

Enter your email address:

Delivered by FeedBurner

Saturday, September 16, 2023

IMPORT CSV DATA USING CODEIGNITER FOUR

 IMPORT CSV Using  CODEIGNITER 4 -


STEP 1-  App Config to Set Base url :

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* http://example.com/
*/
public string $baseURL = 'http://127.0.0.1/importdata/public/';

/**



STEP 2-  Database Define ENV file

#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------

# CI_ENVIRONMENT = production

#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------

# app.baseURL = ''
# If you have trouble with `.`, you could also use `_`.
# app_baseURL = ''
# app.forceGlobalSecureRequests = false
# app.CSPEnabled = false

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

# database.default.hostname = localhost
# database.default.database = import_data
# database.default.username = root
# database.default.password = root
# database.default.DBDriver = MySQLi
# database.default.DBPrefix =
# database.default.port = 3306

# database.tests.hostname = localhost
# database.tests.database = ci4_test
# database.tests.username = root
# database.tests.password = root
# database.tests.DBDriver = MySQLi
# database.tests.DBPrefix =
# database.tests.port = 3306

#--------------------------------------------------------------------
# CONTENT SECURITY POLICY
#--------------------------------------------------------------------

# contentsecuritypolicy.reportOnly = false
# contentsecuritypolicy.defaultSrc = 'none'
# contentsecuritypolicy.scriptSrc = 'self'
# contentsecuritypolicy.styleSrc = 'self'
# contentsecuritypolicy.imageSrc = 'self'
# contentsecuritypolicy.baseURI = null
# contentsecuritypolicy.childSrc = null
# contentsecuritypolicy.connectSrc = 'self'
# contentsecuritypolicy.fontSrc = null
# contentsecuritypolicy.formAction = null
# contentsecuritypolicy.frameAncestors = null
# contentsecuritypolicy.frameSrc = null
# contentsecuritypolicy.mediaSrc = null
# contentsecuritypolicy.objectSrc = null
# contentsecuritypolicy.pluginTypes = null
# contentsecuritypolicy.reportURI = null
# contentsecuritypolicy.sandbox = false
# contentsecuritypolicy.upgradeInsecureRequests = false
# contentsecuritypolicy.styleNonceTag = '{csp-style-nonce}'
# contentsecuritypolicy.scriptNonceTag = '{csp-script-nonce}'
# contentsecuritypolicy.autoNonce = true

#--------------------------------------------------------------------
# COOKIE
#--------------------------------------------------------------------




STEP 3-  To Create Model  ImportModel.php and Define Table Field : 

<?php
namespace App\Models;
use CodeIgniter\Model;
class ImportModel extends Model
{
protected $table = 'students';
protected $primaryKeys = 'id';
protected $allowedFields = [
'name',
'email',
'phone',
'created_at'
];
}




STEP 4-  To Create View index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel Import Excel CSV to MySQL</title>
<meta name="description" content="The tiny framework with powerful features">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="<?php echo base_url('/importdata');?>" 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 5- To Define Routes.php

<?php

use CodeIgniter\Router\RouteCollection;

/**
* @var RouteCollection $routes
*/
// $routes->get('/', 'Home::index');
$routes->get('/', 'ImportController::index');
$routes->post('/importdata', 'ImportController::importCsvToDb');


STEP 5- To Create Controller  ImportController.php:

Focus on Just bellow Code Condition which consider numberOfField from csv file. 

$numberOfFields = 4; ($filedata = fgetcsv($file, 1000, ",")) !== FALSE

<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use App\Models\ImportModel;

class ImportController extends Controller
{
public function index()
{
return view('index');
}
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 ImportModel();
$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 5- To Define Routes.php

No comments:

Post a Comment

Adbox