Do not speak Portuguese? Translate this site with Google or Bing Translator
Import Selected CSV File Column in LARAVEL using Ajax jQuery

Posted on: September 06, 2021 02:18 PM

Posted by: Renato

Categories: Laravel PHP csv

Views: 818

# Import Selected CSV File Column in LARAVEL using Ajax jQuery


> import sample.csv ## About Laravel

Build Status Total Downloads Latest Stable Version License

- https://gitlab.com/cpdrenato/laravel-import-csv

Import Selected CSV File Column in PHP using Ajax jQuery



On the web, we have seen lots of articles or tutorial on How to import CSV file data into Mysql Database by using PHP script. But there are none of the tutorials has define how can we define particular CSV file column data at the time of importing file, and that selected column data has been imported into Mysql table by using PHP script with Ajax jQuery. For solve the problem of CSV file Column Mapping here we have make this tutorial in which we have step by step describe the process of CSV file column mapping in PHP using Ajax jQuery.

This tutorial has divided in following different part.
  • Make Upload Form for Select CSV File
  • Convert CSV File into HTML Table
  • Write jQuery Code for Column Selection
  • Import Select Column Data



Before we have going to step, first we must have to see our database structure. So below you can find this tutorial Mysql table definition.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `csv_file`
--

CREATE TABLE `csv_file` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `csv_file`
--
ALTER TABLE `csv_file`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `csv_file`
--
ALTER TABLE `csv_file`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;


Here in this Mysql table there is only three column in which we want to import CSV file data. Now below we have to CSV file structure.


Company Name,First Name,Last Name,Address,City,State,ZIP/PIN CODE,Country,Phone Number,Email
Prestiga-Biz,Barbara,Motes,3029 Harrison Street,Oakland,CA,94612,USA,415-481-0998,[email protected]
McDade's,Paul,Minter,1376 Orphan Road,Long Lake,WI,54542,USA,715-967-2332,[email protected]
Penn Fruit,Robin,Morton,4609 Eastland Avenue,Jackson,MS,39211,USA,601-348-3248,[email protected]
Frank's Nursery & Crafts,Alvin,Sarvis,83 Star Trek Drive,Pensacola,FL,32501,USA,850-356-1961,[email protected]
Media Play,Daniel,Retana,1114 Bel Meadow Drive,Arrowhead,CA ,92352,USA,909-336-8296,[email protected]
Cut Rite,Eva,Tallent,4138 Shadowmar Drive,Metairie,LA,70006,USA,504-779-1200,[email protected]
Matrix Design,Charles,Astorga,410 Westwood Avenue,Garden City,NY ,11530,USA,516-805-0092,[email protected]
Century House,Jane,Lim,2305 Reppert Coal Road,Southfield,MI,48075,USA,586-970-6260,[email protected]
Life's Gold,Tom,Garcia,518 Seth Street,Gustine,TX,76455,USA,325-667-9370,[email protected]
Two Pesos,Aaron,Lovejoy,2448 Settlers Lane,New York,NY,10007,USA,917-826-2371,[email protected]
Smitty's Marketplace,Susan,Reyes,4402 Stuart Street,Sewickley,PA,15143,USA,724-417-4584,[email protected]
Waves Music,Susan,Jackson,1196 Archwood Avenue,Cheyenne,WY,82003,USA,307-871-1265,[email protected]
Realty Depot,Mary,Shepard,2632 Scott Street,Poughkeepsie,NY,12601,USA,845-471-7357,[email protected]
Martin's,Sadie,Hill,148 Peaceful Lane,Warrensville Heights,OH,44128,USA,216-390-5580,[email protected]
Wickes Furniture,Stephen,Flynn,4378 Jenna Lane,Ames,IA,50010,USA,515-233-9027,[email protected]
Larry's Markets,Beth,Holloway,3915 Essex Court,South Burlington,VT,5403,USA,802-272-7414,[email protected]
Handy Dan,Mildred,Hoyt,2626 Johnstown Road,Cary,IL,60013,USA,847-462-6919,[email protected]
Laura Ashley Mother & Child,Karen,Walker,3659 Shingleton Road,Portage,MI,49002,USA,269-327-9698,[email protected]
Harmony House,Lucille,Wilson,644 Villa Drive,South Bend,IN,46601,USA,574-303-6598,[email protected]
Suadela Investment,Jimmie,Cornwell,2533 Melody Lane,Lively,VA,22503,USA,804-462-5048,[email protected]
American Appliance,Marion,Davis,2905 Denver Avenue,City Of Commerce,CA,90040,USA,951-314-7204,[email protected]
The Warner Brothers Store,Sonia,Johnson,1510 Bel Meadow Drive,Los Angeles,CA,90017,USA,909-269-6784,[email protected]
Gart Sports,Brandy,Voyles,2538 Broadcast Drive,Washington,VA,20011,USA,703-956-0582,[email protected]
Irving's Sporting Goods,Deborah,Gossard,2655 Ashton Lane,Austin,TX,78756,USA,512-465-9149,[email protected]
Yardbirds Home Center,Dawn,Guerrero,753 Saints Alley,Tampa,FL,33614,USA,813-787-0466,[email protected]
Multicerv,Priscilla,Holloway,4957 Custer Street,Smethport,PA,16749,USA,814-887-3339,[email protected]
Colonial Stores,Jay,Crowder,4281 Ryder Avenue,Bellevue,WA,98004,USA,425-384-6261,[email protected]
Balanced Fortune,Ashley,Hemphill,2042 Olen Thomas Drive,Rosston,TX,76263,USA,940-768-7053,[email protected]
Lee Wards,Debra,Harrington,532 Seltice Way,Kellogg,ID,83837,USA,208-783-0049,[email protected]
Garden Guru,Anna,Brooks,1332 Brown Street,San Francisco,CA,94124,USA,925-999-9078,[email protected]



So, Above we can see that there is 10 column in CSV file. Now we have to make feature like when we have upload CSV file file then we can define three column and only three column data must be import into above Mysql table. So below you can find the solution of CSV file column mapping in PHP script using Ajax jQuery.



1 - Make Upload Form for Select CSV File


For make CSV file column mapping script. So first we have to make One upload form for select CSV file from our local computer. After creating HTML form for upload csv file. Then after we have to write jquery code and in that code we have make Ajax call which will send CSV file to server script. Below you can find the source code of this steps.

index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

});
</script>






2 - Convert CSV File into HTML Table


In second steps, First we have to check user has select file or not. If User has select file then we have to check selected file is .csv file or not if selected file is CSV file then we have to fetch data from CSV file. From this first line of csv file, we have to count total number of column of CSV file and based on that column we have to make select box for column selection for all column in html table format. After this all csv file data has been store in SESSION variable for future use of import data and top five row of CSV file has been convert into HTML table. After this we have to make import button and append that button code in HTML table code and send whole data to Ajax request in json string format.




upload.php



<?php

//upload.php

session_start();

$error = '';

$html = '';

if($_FILES['file']['name'] != '')
{
 $file_array = explode(".", $_FILES['file']['name']);

 $extension = end($file_array);

 if($extension == 'csv')
 {
  $file_data = fopen($_FILES['file']['tmp_name'], 'r');

  $file_header = fgetcsv($file_data);

  $html .= '<table class="table table-bordered"><tr>';

  for($count = 0; $count < count($file_header); $count++)
  {
   $html .= '
   <th>
    <select name="set_column_data" class="form-control set_column_data" data-column_number="'.$count.'">
     <option value="">Set Count Data</option>
     <option value="first_name">First Name</option>
     <option value="last_name">Last Name</option>
     <option value="email">Email</option>
    </select>
   </th>
   ';
  }

  $html .= '</tr>';

  $limit = 0;

  while(($row = fgetcsv($file_data)) !== FALSE)
  {
   $limit++;

   if($limit < 6)
   {
    $html .= '<tr>';

    for($count = 0; $count < count($row); $count++)
    {
     $html .= '<td>'.$row[$count].'</td>';
    }

    $html .= '</tr>';
   }

   $temp_data[] = $row;
  }

  $_SESSION['file_data'] = $temp_data;

  $html .= '
  </table>
  <br />
  <div align="right">
   <button type="button" name="import" id="import" class="btn btn-success" disabled>Import</button>
  </div>
  <br />
  ';
 }
 else
 {
  $error = 'Only <b>.csv</b> file allowed';
 }
}
else
{
 $error = 'Please Select CSV File';
}

$output = array(
 'error'  => $error,
 'output' => $html
);

echo json_encode($output);


?>



3 - Write jQuery Code for Column Selection


Once selected CSV file data has been uploaded and after this convert that file data into html table format and display on web page. Now in third step we have to write jquery code for validate column selection or mapping. So, we have to write jquery script, firts it will check user must have to select at least three column this is because in database there is three column in which we want to import data. If user select less than or greater than three column then import button will be disabled, but if user select three different column then import button will enable. jQuery will also check user must define define unique column as per Mysql table, if user select two column from html table with same Mysql table then also import button will disable. All unique column select box option we have to store in variable, and this variable value we will be used for define column number at the time of importing of data. So this validation will check in this part of jQuery script.



index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });
  
});
</script>



4 - Import Select Column Data


This is last part of CSV file column mapping tutorial and in this part we have to import selected CSV file column data into Mysql table. In third part, we have write jQuery script and define three column with unique option. Now in this part, we have to write jQuery script in which we have to make Ajax call which will send local variable in which we have store column number which has been get in third part. Based on this variable column number at PHP script will import only that column data into Mysql table. At PHP script CSV file data will be get from SESSION variable in which we have store CSV file data in second steps.




index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });

  $(document).on('click', '#import', function(event){

    event.preventDefault();

    $.ajax({
      url:"import.php",
      method:"POST",
      data:{first_name:first_name, last_name:last_name, email:email},
      beforeSend:function(){
        $('#import').attr('disabled', 'disabled');
        $('#import').text('Importing...');
      },
      success:function(data)
      {
        $('#import').attr('disabled', false);
        $('#import').text('Import');
        $('#process_area').css('display', 'none');
        $('#upload_area').css('display', 'block');
        $('#upload_form')[0].reset();
        $('#message').html("<div class='alert alert-success'>"+data+"</div>");
      }
    })

  });
  
});
</script>


import.php



<?php

//import.php

if(isset($_POST["first_name"]))
{
 $connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

 session_start();

 $file_data = $_SESSION['file_data'];

 unset($_SESSION['file_data']);

 foreach($file_data as $row)
 {
  $data[] = '("'.$row[$_POST["first_name"]].'", "'.$row[$_POST["last_name"]].'", "'.$row[$_POST["email"]].'")';
 }

 if(isset($data))
 {
  $query = "
  INSERT INTO csv_file 
  (first_name, last_name, email) 
  VALUES ".implode(",", $data)."
  ";

  $statement = $connect->prepare($query);

  if($statement->execute())
  {
   echo 'Data Imported Successfully';
  }
 }
}



?>


So, In this tutorial, we have step by step sees how can we map CSV file column or define CSV file column and then after we have import or insert that define or selected column data into Mysql table by using PHP with Ajax jQuery. IF you have find any simple way for map csv file column in PHP then you are welcome and Let us know in the comments section.
Fonte: - https://gitlab.com/cpdrenato/laravel-import-csv - https://blog.renatolucena.net/

- https://www.webslesson.info/2020/06/import-selected-csv-file-column-in-php-using-ajax-jquery.html

- Renato Lucena


3

Share

Donate to Site


About Author

Renato

Developer

Add a Comment
Comments 0 Comments

No comments yet! Be the first to comment

Blog Search


Categories

OUTROS (15) Variados (109) PHP (130) Laravel (157) Black Hat (3) front-end (28) linux (111) postgresql (39) Docker (25) rest (5) soap (1) webservice (6) October (1) CMS (2) node (7) backend (13) ubuntu (54) devops (25) nodejs (5) npm (2) nvm (1) git (8) firefox (1) react (6) reactnative (5) collections (1) javascript (6) reactjs (7) yarn (0) adb (1) Solid (2) blade (3) models (1) controllers (0) log (0) html (2) hardware (3) aws (14) Transcribe (2) transcription (1) google (4) ibm (1) nuance (1) PHP Swoole (5) mysql (31) macox (4) flutter (1) symfony (1) cor (1) colors (2) homeOffice (2) jobs (3) imagick (2) ec2 (1) sw (1) websocket (1) markdown (1) ckeditor (1) tecnologia (14) faceapp (1) eloquent (14) query (4) sql (40) ddd (3) nginx (9) apache (4) certbot (1) lets-encrypt (3) debian (11) liquid (1) magento (2) ruby (1) LETSENCRYPT (1) Fibonacci (1) wine (1) transaction (1) pendrive (1) boot (1) usb (1) prf (1) policia (2) federal (1) lucena (1) mongodb (4) paypal (1) payment (1) zend (1) vim (4) ciencia (6) js (1) nosql (1) java (1) JasperReports (1) phpjasper (1) covid19 (1) saude (1) athena (1) cinnamon (1) phpunit (2) binaural (1) mysqli (3) database (42) windows (6) vala (1) json (2) oracle (1) mariadb (4) dev (12) webdev (24) s3 (4) storage (1) kitematic (1) gnome (2) web (2) intel (3) piada (1) cron (2) dba (18) lumen (1) ffmpeg (2) android (2) aplicativo (1) fedora (2) shell (4) bash (3) script (3) lider (1) htm (1) csv (1) dropbox (1) db (3) combustivel (2) haru (1) presenter (1) gasolina (1) MeioAmbiente (1) Grunt (1) biologia (1) programming (22) performance (3) brain (1) smartphones (1) telefonia (1) privacidade (1) opensource (3) microg (1) iode (1) ssh (3) zsh (2) terminal (3) dracula (1) spaceship (1) mac (2) idiomas (1) laptop (2) developer (37) api (4) data (1) matematica (1) seguranca (2) 100DaysOfCode (9) hotfix (1) documentation (1) laravelphp (10) RabbitMQ (1) Elasticsearch (1) redis (2) Raspberry (4) Padrao de design (4) JQuery (1) angularjs (4) Dicas (37) Kubernetes (2) vscode (2) backup (1) angular (3) servers (2) pipelines (1) AppSec (1) DevSecOps (4) rust (1) RustLang (1) Mozilla (1) algoritimo (1) sqlite (1) Passport (1) jwt (4) security (2) translate (1) kube (1) iot (1) politica (2) bolsonaro (1) flow (1) podcast (1) Brasil (1) containers (2) traefik (1) networking (1) host (1) POO (2) microservices (2) bug (1) cqrs (1) arquitetura (2) Architecture (3) sail (3) militar (1) artigo (1) economia (1) forcas armadas (1) ffaa (1) autenticacao (1) autorizacao (2) authentication (4) authorization (2) NoCookies (1) wsl (4) memcached (1) macos (2) unix (2) kali-linux (1) linux-tools (5) apple (1) noticias (2) composer (1) rancher (1) k8s (1) escopos (1) orm (1) jenkins (4) github (5) gitlab (3) queue (1) Passwordless (1) sonarqube (1) phpswoole (1) laraveloctane (1) Swoole (1) Swoole (1) octane (1) Structurizr (1) Diagramas (1) c4 (1) c4-models (1) compactar (1) compression (1) messaging (1) restfull (1) eventdrive (1) services (1) http (1) Monolith (1) microservice (1) historia (1) educacao (1) cavalotroia (1) OOD (0) odd (1) chatgpt (1) openai (3) vicuna (1) llama (1) gpt (1) transformers (1) pytorch (1) tensorflow (1) akitando (1) ia (1) nvidia (1) agi (1) guard (1) multiple_authen (2) rpi (1) auth (1) auth (1) livros (2) ElonMusk (2) Oh My Zsh (1) Manjaro (1) BigLinux (2) ArchLinux (1) Migration (1) Error (1) Monitor (1) Filament (1) LaravelFilament (1) replication (1) phpfpm (1) cache (1) vpn (1) l2tp (1) zorin-os (1) optimization (1) scheduling (1) monitoring (2) linkedin (1) community (1) inteligencia-artificial (2) wsl2 (1) maps (1) API_KEY_GOOGLE_MAPS (1) repmgr (1) altadisponibilidade (1) banco (1) modelagemdedados (1) inteligenciadedados (4) governancadedados (1) bancodedados (2) Observability (1) picpay (1) ecommerce (1)

New Articles



Get Latest Updates by Email