How to Import CSV File Data into MySQL Database using PHP

A CSV (comma-separated values) file stores the tabular data in plain text format. Basically, CSV file format is used to import to or export from the table data. Each line of the CSV file is a data record that consists of one or more fields. When there is needed to add the huge data into the MySQL database, it’s very time-consuming to add data one by one. In that situation, import feature helps to insert a bunch of data in one click.

Using CSV file you can store all 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 and import CSV file data into MySQL database using PHP.

Here we’ll build an example script to import members data into the database. According to this script functionality, the user would be able to upload a CSV file of members details and members data would be inserted into the MySQL database using PHP.

Create Database Table

You should create a table (members) in the database to store the member’s data. The following SQL creates a members table with some basic fields.

CREATE TABLE `members` (
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Connect to the Database (dbConfig.php)

The dbConfig.php helps to connect and select the database.

//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '';
$dbName 'codexworld';

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
"Unable to connect database: " $db->connect_error);

CSV File Upload (index.php)

In this file, existing members are listed with the Import Members link. Once Import Members link is clicked, a form will appear to choose and upload a .csv file. This form would be submitted to the importData.php file for importing the member’s data to the database.

//load the database configuration file
include 'dbConfig.php';

$statusMsgClass 'alert-success';
$statusMsg 'Members data has been inserted successfully.';
$statusMsgClass 'alert-danger';
$statusMsg 'Some problem occurred, please try again.';
$statusMsgClass 'alert-danger';
$statusMsg 'Please upload a valid CSV file.';
$statusMsgClass '';
$statusMsg '';
?> <div class="container">     <?php if(!empty($statusMsg)){
'<div class="alert '.$statusMsgClass.'">'.$statusMsg.'</div>';
?> <div class="panel panel-default"> <div class="panel-heading"> Members list <a href="javascript:void(0);" onclick="$('#importFrm').slideToggle();">Import Members</a> </div> <div class="panel-body"> <form action="importData.php" method="post" enctype="multipart/form-data" id="importFrm"> <input type="file" name="file" /> <input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT"> </form> <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Created</th> <th>Status</th> </tr> </thead> <tbody>                 <?php
//get records from database
$query $db->query("SELECT * FROM members ORDER BY id DESC");
$query->num_rows 0){ 
$row $query->fetch_assoc()){ ?> <tr> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['phone']; ?></td> <td><?php echo $row['created']; ?></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> </div> </div>

The bootstrap table structure is used in the above HTML. So, don’t forget to include the bootstrap libraries.

<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>

Import CSV Data to Database (importData.php)

The following works are processed in this file.

  • Validates the uploaded file whether it is a valid .csv file.
  • The is_uploaded_file() function is checks whether the CSV file is uploaded via HTTP POST.
  • The fopen() function opens the CSV file in read-only mode.
  • The fgetcsv() function is used to parse the member’s data from the open CSV file. This function is called in the while loop to parse data from CSV file.
  • Members data are inserted into the database using PHP and MySQL.
  • At last, the user is redirected to the index.php page with importing status code.
//load the database configuration file
include 'dbConfig.php';

//validate whether uploaded file is a csv file
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
$_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
//open uploaded csv file with read only mode
$csvFile fopen($_FILES['file']['tmp_name'], 'r');
//skip first line
//parse data from csv file line by line
while(($line fgetcsv($csvFile)) !== FALSE){
                //check whether member already exists in database with same email
$prevQuery "SELECT id FROM members WHERE email = '".$line[1]."'";
$prevResult $db->query($prevQuery);
$prevResult->num_rows 0){
//update member data
$db->query("UPDATE members SET name = '".$line[0]."', phone = '".$line[2]."', created = '".$line[3]."', modified = '".$line[3]."', status = '".$line[4]."' WHERE email = '".$line[1]."'");
//insert member data into database
$db->query("INSERT INTO members (name, email, phone, created, modified, status) VALUES ('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[3]."','".$line[4]."')");
//close opened csv file

$qstring '?status=succ';
$qstring '?status=err';
$qstring '?status=invalid_file';

//redirect to the listing page
header("Location: index.php".$qstring);


We hope this script will help you to implement the import feature in your web project easily. Here we’ve discussed the CSV import to MySQL, you can add more fields or restrictions on data import based on your requirement.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Mike Stewart Said...
  2. Pia Said...
  3. Jorge Said...
  4. Walter Said...
    • CodexWorld Said...
  5. Michiel Van Erven Said...
  6. Michieil Van Erven Said...
    • CodexWorld Said...
  7. Michieil Van Erven Said...
    • CodexWorld Said...
  8. Patrick Said...
  9. Brian Said...
    • CodexWorld Said...
  10. Zerohl Said...
  11. Kanchana Said...
  12. Ruben Said...
  13. Jay Said...
  14. Mark Vickers Said...
    • CodexWorld Said...
  15. Sayyad Mosin Said...
    • CodexWorld Said...

Leave a reply