etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

How to import a CSV file into MySQL using PHP

In this article, you will learn how to read a CSV file using the PHP programming language and store the CSV data in MySQL database.

The CSV stands for "Comma-separated-values", as it uses a comma to separate values. This is a widely used file format that stores data in a tabular format. We generally use this in business, data-based applications for data exchange. Most organisations are web-based, so there may also be a common need to import data from a spreadsheet or a CSV file to a database. The data in a CSV is stored as sequences of records. With the help of PHP, we can easily store each comma-separated sequence in a database row.




Suppose we have the following data stored in a CSV file -

Anjali,This email address is being protected from spambots. You need JavaScript enabled to view it.,878433948
Priska,This email address is being protected from spambots. You need JavaScript enabled to view it.,493905490
Abhi,This email address is being protected from spambots. You need JavaScript enabled to view it.,403022139
Smith,This email address is being protected from spambots. You need JavaScript enabled to view it.,504903904

How to read CSV file in PHP and store in MySQL



Here is the script with a step-by-step code explanation. First, we create a main file 'index.php' that we will call in the browser. In this, we take an HTML file upload form with a submit button.

index.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<form class="md-form"  action='#' method="post" enctype="multipart/form-data">
    <div class="file-field">
    <div class="btn btn-primary btn-sm float-left">
      <span>Choose file</span>
      <input type="file" name="file">
    </div>
    </div><br/><br/>
    <div class="form-group">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>
</body>
</html>

At the top of the 'index.php' page, we have used two PHP constants UPLOAD_DIR and MAXSIZE to define the upload directory and maximum allowed file size limit respectively.

define('UPLOAD_DIR',  '/var/uploaded_files/');
define('MAXSIZE', 7340032); // allow max 7 MB

Next, we have defined all the allowed file extensions in an array $ALLOWED_FILEEXT and all the allowed MIME types in an array $ALLOWED_MIME.

$ALLOWED_MIME = array('text/comma-separated-values', 'text/csv', 'text/plain',
	'application/csv', 'application/excel',
	'application/vnd.ms-excel', 'application/vnd.msexcel');



Next, we create a function name 'allowedfile()' in the same 'index.php' file that accepts a temporary file name and destination path as parameters. In this, we got the uploaded file extension using the PHP predefined function pathinfo() and the mime type of the uploaded file using mime_content_type() function. The allowedfile() function returns TRUE if both file extension and MIME type of the uploaded file are allowed.

function allowedfile($tempfile, $destpath) {
 global $ALLOWED_MIME;
 $file_ext = pathinfo($destpath, PATHINFO_EXTENSION); 
 $file_mime = mime_content_type($tempfile);
 $valid_mime = in_array($file_mime, $ALLOWED_MIME);
 $allowed_file = ($file_ext == 'csv') && $valid_mime;
 return $allowed_file;
}

Next, create a function 'handleUpload()' and validate the file size and call the 'allowedfile()' function within it before moving the file to its destination.

function handleUpload() {
 $temp = $_FILES['file']['tmp_name'];
 $filename = basename($_FILES['file']['name']);
 $file_dest = UPLOAD_DIR. $filename;
 $is_uploaded = is_uploaded_file($temp); 
 $valid_size = $_FILES['file']['size'] <= MAXSIZE && $_FILES['file']['size'] >= 0;
	
 if ($is_uploaded && $valid_size && allowedfile($temp, $file_dest)) {
  move_uploaded_file($temp, $file_dest);
  insertCSV($file_dest);
 } else {
  $response = 'Error: uploaded file size or type is not valid.';
 }
 return $response;
}




Here, we have added different error handling cases and called 'handleUpload()' within one of the cases. PHP returns an appropriate error code along with the file array. It is found in the file error segment or, $_FILES['file']['error'], that returns the error code if any problem is created during the file upload.

// Handle Error
if (!empty($_FILES)) {
 echo $error = $_FILES['file']['error'];
 switch($error) {
  case UPLOAD_ERR_OK:
  $response = handleUpload();
  break;
  case UPLOAD_ERR_INI_SIZE:
  $response = 'Error: file size exceeds the allowed.';
  break;
  default:
  $response = 'An unexpected error occurred; the file could not be uploaded.';
  break;
}
} else {
  $response = 'Please upload CSV file';
}
echo $response;	

Next, we have created a function 'insertCSV()' to store data in the database. Here is the table structure, you can either copy paste this in your database, or you can use your existing MySQL table.

CREATE TABLE IF NOT EXISTS `empdata` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(25) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

function insertCSV($filename){ 
$conn = mysqli_connect('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
if($fileHandle = fopen($filename, "r")){
 while(($row = fgetcsv($fileHandle, 0, ",")) !== FALSE)
 {
  $insert = "INSERT into empdata(name,email,phone) values('$row[0]','$row[1]','$row[2]')";
  if(mysqli_query($conn, $insert)){
   echo 'Data inserted successfully';
  }
  else{
   echo 'Error: '.mysqli_error($conn);
  }
 }
 fclose($fileHandle);
  echo "CSV File has been successfully Imported.";
}
}




Complete Code: How to read a CSV file in PHP and store in MySQL

Here, we have merged all codes that were explained in detail above to read uploaded CSV file and import it in the database using PHP. Make sure to replace 'hostname', 'username', 'password' and 'database' with your credentials.

<?php 
// Define constants
define('UPLOAD_DIR', '/var/uploaded_files/');
define('MAXSIZE', 7340032); // allow max 7 MB

// allowed file types
$ALLOWED_MIME = array('text/comma-separated-values', 'text/csv', 'text/plain',
					'application/csv', 'application/excel',
					'application/vnd.ms-excel', 'application/vnd.msexcel');

// Handling Error
if (!empty($_FILES)) {
	echo $error = $_FILES['file']['error'];
	switch($error) {
		case UPLOAD_ERR_OK:
		$response = handleUpload();
		break;
		case UPLOAD_ERR_INI_SIZE:
		$response = 'Error: file size exceeds the allowed.';
		break;
		default:
		$response = 'An unexpected error occurred; the file could not be uploaded.';
		break;
	}
} else {
	$response = 'Please upload CSV file';
}
echo $response;					
			
// allowed file extension		
function allowedfile($tempfile, $destpath) {
	global $ALLOWED_MIME;
	$file_ext = pathinfo($destpath, PATHINFO_EXTENSION); 
	$file_mime = mime_content_type($tempfile);
	$valid_mime = in_array($file_mime, $ALLOWED_MIME);
	$allowed_file = ($file_ext == 'csv') && $valid_mime;
	return $allowed_file;
}	

// handling file upload		
function handleUpload() {
	$temp = $_FILES['file']['tmp_name'];
	$filename = basename($_FILES['file']['name']);
	$file_dest = UPLOAD_DIR. $filename;
	$is_uploaded = is_uploaded_file($temp); 
	$valid_size = $_FILES['file']['size'] <= MAXSIZE && $_FILES['file']['size'] >= 0;
	
	if ($is_uploaded && $valid_size && allowedfile($temp, $file_dest)) {
		move_uploaded_file($temp, $file_dest);
	    insertCSV($file_dest);
	} else {
		$response = 'Error: uploaded file size or type is not valid.';
	}
	return $response;
}	

// store data in database
function insertCSV($filename){ 
$conn = mysqli_connect('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
if($fileHandle = fopen($filename, "r")){
	while(($row = fgetcsv($fileHandle, 0, ",")) !== FALSE)
	{
	$insert = "INSERT into empdata(name,email,phone) values('$row[0]','$row[1]','$row[2]')";
 	if(mysqli_query($conn, $insert)){
	 echo 'Data inserted successfully';
	}
	else{
	 echo 'Error: '.mysqli_error($conn);
	}
	}
	fclose($fileHandle);
	echo "CSV File has been successfully Imported.";
}
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<form class="md-form"  action='#' method="post" enctype="multipart/form-data">
	<div class="file-field">
    <iv class="btn btn-primary btn-sm float-left">
      <span>Choose file</span>
      <input type="file" name="file">
    </div>
	</div><br/><br/>
    <div class="form-group">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>
</body>
</html>




Related Articles

PHP program to reverse a string
PHP remove last character from string
Export data from MySQL table to CSV file using PHP
PHP Fix: invalid argument supplied for foreach
PHP Connection and File Handling on FTP Server
Django Export Model Data to CSV
Convert Excel to CSV Python Pandas
Ajax live data search using jQuery PHP MySQL
PHP File Upload MIME Type Validation with Error Handler
How to display PDF file in PHP from database
File Upload Validation in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
jQuery File upload progress bar with file size validation
Simple star rating system using PHP, jQuery and Ajax
JavaScript display PDF in the browser using Ajax call
jQuery loop over JSON result after AJAX Success




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
How to print specific part of a web page in javascript
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
How to display PDF file in web page from Database in PHP
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.