Import CSV File Data Using MySql And PHP

This is simple code to Import CSV file data using MySql and PHP, Here we are taking the data from the CSV file and inserting it into the database. This is the beginner level code.

Create the following files

  1. upload.php
  2. create csv file with two columns of data

Code to Import CSV file data using MySql and PHP

[php] <?php if ($_FILES[csv][size] > 0) {

//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");

//loop through the csv file and insert into database
do {
if ($data[0]) {
echo $sql = "INSERT INTO contacts (name, email) VALUES
} while ($data = fgetcsv($handle,1000,",","’"));

header(‘Location: import.php?success=1’); die;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>


<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />


This is sample code to display the csv data into an array, after that you can manipulate the data and excute the query.

Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.