Skip to content Skip to sidebar Skip to footer

How to Upload File From User With Fgetcsv Php

Import CSV File into MySQL using PHP

by Vincy. Last modified on May 26th, 2021.

In this tutorial, I volition walk yous through PHP code to import CSV file into MySQL database past parsing the comma-separated data. The input CSV file is sent via a HTML form. There are various ways to read the CSV data and bank check my previous linked article for a different option.

I usedfgetcsv()function to read the database table column information from the CSV.

If yous are looking for PHP code to restore SQL script into database, please check my previous article example of restoring the database by importing the SQL script.

This Screenshot displays the list of imported CSV information from the database after successful CSV file import.

import-csv-file-into-mysql-using-php-output

HTML Form to Import CSV File

This HTML code is used to bear witness a form with the CSV file import option. After submitting the file, PHP lawmaking parses the CSV information and prepares INSERT query to load the data into the database.

After importing the information into the database the added rows are listed in the browser. When the user uploads the CSV source, the file type is restricted by specifying .csv using the have attribute.

Subsequently importing the complete data from the CSV file it displays the stored data in a grid view. The lawmaking to recall the stored data and the grid view is every bit follows.

<h2>Import CSV file into Mysql using PHP</h2>      <div id="response"         class="<?php if(!empty($type)) { echo $type . " brandish-cake"; } ?>">         <?php if(!empty($message)) { repeat $bulletin; } ?>         </div>     <div class="outer-scontainer">         <div form="row">              <form class="course-horizontal" action="" method="postal service"                 name="frmCSVImport" id="frmCSVImport"                 enctype="multipart/class-data">                 <div class="input-row">                     <label class="col-doc-4 control-label">Cull CSV                         File</label> <input type="file" name="file"                         id="file" have=".csv">                     <push type="submit" id="submit" name="import"                         class="btn-submit">Import</button>                     <br />                  </div>              </form>          </div>                <?php             $sqlSelect = "SELECT * FROM users";             $result = $db->select($sqlSelect);             if (! empty($result)) {                 ?>             <table id='userTable'>             <thead>                 <tr>                     <th>User ID</th>                     <th>User Name</th>                     <th>First Proper noun</th>                     <th>Concluding Proper noun</th>                  </tr>             </thead> <?php                                  foreach ($upshot every bit $row) {                     ?>                                      <tbody>                 <tr>                     <td><?php  echo $row['userId']; ?></td>                     <td><?php  echo $row['userName']; ?></td>                     <td><?php  echo $row['firstName']; ?></td>                     <td><?php  echo $row['lastName']; ?></td>                 </tr>                     <?php                 }                 ?>                 </tbody>         </table>         <?php } ?>     </div>        

The jQuery validation for checking the uploaded file type is done by using regex. It checks if the uploaded file is with the .csv extension.

If so, information technology will allow further default action to submit the file binaries to the PHP. Otherwise, information technology stops form submit and displays the error to the browser.

<script type="text/javascript"> $(document).ready(function() {     $("#frmCSVImport").on("submit", role () {  	    $("#response").attr("class", "");         $("#response").html("");         var fileType = ".csv";         var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + fileType + ")$");         if (!regex.test($("#file").val().toLowerCase())) {         	    $("#response").addClass("fault");         	    $("#response").addClass("display-cake");             $("#response").html("Invalid File. Upload : <b>" + fileType + "</b> Files.");             return fake;         }         return true;     }); }); </script>        

PHP Code to Import CSV Data to MySQL

In PHP code, information technology reads the uploaded CSV file and parses the information. It opens the input file in reading mode and gets the cavalcade data using fgetcsv().

It keeps on proceed this process in a loop until information technology reaches the terminate of the CSV file. For each iteration. it gets the assortment of column information of a unmarried record. It prepares INSERT query using these data and executes it to load the information into the database.

<?php use Phppot\DataSource;  require_once 'DataSource.php'; $db = new DataSource(); $conn = $db->getConnection();  if (isset($_POST["import"])) {          $fileName = $_FILES["file"]["tmp_name"];          if ($_FILES["file"]["size"] > 0) {                  $file = fopen($fileName, "r");                  while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {                          $userId = "";             if (isset($column[0])) {                 $userId = mysqli_real_escape_string($conn, $column[0]);             }             $userName = "";             if (isset($column[1])) {                 $userName = mysqli_real_escape_string($conn, $column[1]);             }             $password = "";             if (isset($column[2])) {                 $password = mysqli_real_escape_string($conn, $column[two]);             }             $firstName = "";             if (isset($column[3])) {                 $firstName = mysqli_real_escape_string($conn, $column[3]);             }             $lastName = "";             if (isset($column[iv])) {                 $lastName = mysqli_real_escape_string($conn, $column[4]);             }                          $sqlInsert = "INSERT into users (userId,userName,countersign,firstName,lastName)                    values (?,?,?,?,?)";             $paramType = "issss";             $paramArray = array(                 $userId,                 $userName,                 $password,                 $firstName,                 $lastName             );             $insertId = $db->insert($sqlInsert, $paramType, $paramArray);                          if (! empty($insertId)) {                 $type = "success";                 $message = "CSV Data Imported into the Database";             } else {                 $blazon = "error";                 $message = "Trouble in Importing CSV Data";             }         }     } } ?>        

Download

↑ Back to Superlative

sandstromcovir1963.blogspot.com

Source: https://phppot.com/php/import-csv-file-into-mysql-using-php/

Post a Comment for "How to Upload File From User With Fgetcsv Php"