A CSV (comma-separated values) file stores the tabular data in plain text format. Mostly, the CSV file format is used to import or export data in the web application. Each line of the CSV file is a data record that consists of one or more fields. When there is needed to add huge data into the MySQL database, it will very time-consuming to add data one by one. In that situation, the import feature helps to insert a bunch of data in the database with a single click.
Bulk Import is a very useful feature to add multiple records in the database without insert manually. Using the CSV file you can store the data and import the CSV file data into the database at once using PHP and MySQL. Import CSV into MySQL helps to save the user time and avoid repetitive work. In this tutorial, we will show you how to upload CSV file and import data from CSV file to MySQL database using PHP.
In the example script, we will import the member’s data from a CSV file and insert it into the database using PHP and MySQL. According to this script functionality, the user can upload a CSV file that holds member records, and import bulk members data in the MySQL database using PHP.
To store the member’s records, a table is required in the database. The following SQL creates a members
table with some basic fields in the MySQL database.
CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`phone` varchar(15) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`status` tinyint(1) DEFAULT NULL COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Based on the database table structure, the CSV file should have the following fields:
To import the data from a CSV file, the format must be similar to the following screen.
The dbConfig.php
is used to connect and select the database. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL database credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "codexworld"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
Initially, the existing member’s records are listed with CSV file import option.
importData.php
file for importing the CSV data to the database.If the form has already been submitted, the submission status is retrieved from SESSION and displayed on the web page.
<?php
// Start session
if(!session_id()){
session_start();
}
// Load the database configuration file
include_once 'dbConfig.php';
// Get status message
if(!empty($_SESSION['response'])){
$status = $_SESSION['response']['status'];
$statusMsg = $_SESSION['response']['msg'];
unset($_SESSION['response']);
}
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="col-xs-12">
<div class="alert alert-<?php echo $status; ?>"><?php echo $statusMsg; ?></div>
</div>
<?php } ?>
<div class="row">
<!-- Import link -->
<div class="col-md-12 head">
<div class="float-end">
<a href="javascript:void(0);" class="btn btn-primary" onclick="formToggle('importFrm');"><i class="plus"></i> Import</a>
</div>
</div>
<!-- CSV file upload form -->
<div class="col-md-12" id="importFrm" style="display: none;">
<form action="importData.php" method="post" class="row g-2 float-end" enctype="multipart/form-data">
<div class="col-auto">
<input type="file" name="file" class="form-control" required/>
<!-- Link to download sample format -->
<p class="text-start mb-0 mt-2">
<a href="sample-csv-members.csv" class="link-primary" download>Download Sample Format</a>
</p>
</div>
<div class="col-auto">
<input type="submit" class="btn btn-success mb-3" name="importSubmit" value="Import CSV">
</div>
</form>
</div>
<!-- Data list table -->
<table class="table table-striped table-bordered">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
// Fetch member records from database
$result = $db->query("SELECT * FROM members ORDER BY id DESC");
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?php echo '#'.$row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td><?php echo $row['status'] == 1?'Active':'Inactive'; ?></td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No member(s) found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
<!-- Show/hide CSV upload form -->
<script>
function formToggle(ID){
var element = document.getElementById(ID);
if(element.style.display === "none"){
element.style.display = "block";
}else{
element.style.display = "none";
}
}
</script>
The importData.php
file handles the file upload and CSV data import operations using PHP and MySQL.
<?php
// Start session
if(!session_id()){
session_start();
}
// Load the database configuration file
include_once 'dbConfig.php';
$res_status = $res_msg = '';
if(isset($_POST['importSubmit'])){
// Allowed mime types
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel');
// Validate whether selected file is a CSV file
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
// If the file is uploaded
if(is_uploaded_file($_FILES['file']['tmp_name'])){
// Open uploaded CSV file with read-only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
// Skip the first line
fgetcsv($csvFile);
// Parse data from CSV file line by line
while(($line = fgetcsv($csvFile)) !== FALSE){
$line_arr = !empty($line)?array_filter($line):'';
if(!empty($line_arr)){
// Get row data
$name = trim($line_arr[0]);
$email = trim($line_arr[1]);
$phone = trim($line_arr[2]);
$status = trim($line_arr[3]);
// Check whether member already exists in the database with the same email
$prevQuery = "SELECT id FROM members WHERE email = '".$email."'";
$prevResult = $db->query($prevQuery);
if($prevResult->num_rows > 0){
// Update member data in the database
$db->query("UPDATE members SET name = '".$name."', phone = '".$phone."', status = '".$status."', modified = NOW() WHERE email = '".$email."'");
}else{
// Insert member data in the database
$db->query("INSERT INTO members (name, email, phone, created, modified, status) VALUES ('".$name."', '".$email."', '".$phone."', NOW(), NOW(), '".$status."')");
}
}
}
// Close opened CSV file
fclose($csvFile);
$res_status = 'success';
$res_msg = 'Members data has been imported successfully.';
}else{
$res_status = 'danger';
$res_msg = 'Something went wrong, please try again.';
}
}else{
$res_status = 'danger';
$res_msg = 'Please select a valid CSV file.';
}
// Store status in SESSION
$_SESSION['response'] = array(
'status' => $res_status,
'msg' => $res_msg
);
}
// Redirect to the listing page
header("Location: index.php");
exit();
?>
Export Data to CSV File using PHP and MySQL
Here, we have tried to make the CSV import process simple. The example code will help you to implement the import functionality in the web application. You can easily enhance our CSV Import to MySQL script functionality, to add more fields or restrictions on data import based on your requirements. If you are looking to export data from Excel file, use this script – Import Excel File Data into MySQL Database using PHP
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Lovely Script and clear to understand, Thanks a lot from Eswatini.
Please how can import csv file into database using php pdo dbh?
Please help me how to remove the email option and add data without email.
How i do set maximum limit in import csv file
// Check whether member already exists in the database with the same email
$prevQuery = “SELECT id FROM members WHERE email = ‘”.$line[1].”‘”;
$prevResult = $db->query($prevQuery);
if($prevResult->num_rows > 0){
pls from the code segment above , i need to read out certai field for certian operation beofre update query is done, pls elp me
This skip the first line of csv file?
i can i signup on this site
Awesome tutorial. I got my thing linked and working. Wonderful.!!!!!!!!!!!!!!!!!
Thank you for the great tutorial and code.
Can you please share the style.css file?
Thanks
Nice tutorial guys. Is that a way to limit the number of records from csv file to mysql database? For example, my system just accept 20 records to upload. Is that possible? Thanks 🙂
its awesome work, and really its very useful who want import csv data in specific table with customization.
Thank you very much is’t so clearly and already run at 2019
Wow Fantastic. This code really works for me. Thank You CODEXWORLD for this fantastic code.
Thank you bro, its working greatttt…..
Excellent clear and clean script. But what happens if you want to update a member’s email address?
thank you for code and demo. its really helpful.
Hi nice tutorial!!
Its there a way to upload the file csv with characters like: canción, nación, España, niño ?
I tried with these tutorial but the characters appears like : canci , naci, Espa, ni
Thank you
Hello a query that surely should be easy to solve but I do not know how to do.
What happens when I import the csv does not show the date and time and only shows
0000-00-00 00:00:00
Probably the DateTime format provided in the CSV file is not matched with DateTime column in the database. Check whether the DateTime value in the CSV file is provided in this format –
24-06-2017 14:58:00
It works. Thank you!
In reply to my previous question: Thanks for the fast answer.
I do see the check e-mail statement. I’ve tried to rule them out. But somehow I get confused by the if..else statement.
Placed a comment marker // at lines (21,22,23,24,25 and 26) But this seems to break up the page.
Thank you in advance.
Michiel.
Open the
importData.php
file, remove the code from line 20 to 29 and place the following code.Hello,
First, thanks for this one. As said before, a good script for starters.
I’ve downloaded the code, everything runs fine.
Copied the csv file, renamed it to memebers2.csv and altered some names.
The import runs fine, but does not add records. (it looks like the former records are overwriten)
In other words: importing file1.csv (with 3 records) and file2.csv (with 6 records) gives me 6 records, instead of 9.
At a second attempt: importint file2.csv (6 records) and file1.csv (3 records) the database stil shows me the first 6 records instead of 9
Any help would be appreciated.
@Michieil As per our example script, if a member record already exists with same email address, this member record will be updated. If you want to add multiple records with the same email, remove the duplicate email checking.
Very nice tutorial! Thank you very much for that.
Can you please give me a hint how to change the fgetcsv delimiter to semicolon?
In the php docs I can see the Parameters – perhaps I miss something in your code.
Hi,
Trying this, but in my case & in the demo, both say “Please upload a valid CSV file.”
100% sure its valid.
Whats wrong? Code is not altered.
– Thanks
@Brian We’ve modified the script with the updated CSV mimes ($csvMimes), please use the latest script.
Hi, i’am a beginner. Could you illustrate me the mean of the $line[4], $line[3], ecc? I need to load a csv and after update all the data of a table with another csv upload. Thanks.
this is great. very simple and clear code. it works nice. thank you very much for your effort.
Really. this was very help full. i just add the php mailer (mail). just before of //close opened csv file
fclose($csvFile); , and just do exactly what i want.
Thank you for your effort of distributing good works and useful ready-to-use codes for us. 🙂
Thank you so much for this demo!
It’s the only one out of a dozen that I’ve tried that did what it promised, faultlessly.
As Sayyad said, if and when you have some code that helps me prevent people from uploading duplicate data, that would be a massive help.
Cheers,
(BTW, there’s no button here for me to receive email updates from the page – do they happen automatically? Or do I need to keep checking back?)
@Mark We’ve updated the code with your requested functionality, download the latest version of the script.
if data is already exist then it must be update can u please share the code for that..
We’ll try to update our script with this functionality soon.