How To Import CSV file data in mysql database using PHP

04/03/2017   11:28:29 AM

Hello, in this tutorial I will explain how to import csv file data in mysql database using PHP. 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.

Save file in csv (comma-separated values) format.

1) Creating Database Table

  • First create a database then create table inside your database. I have created a sampledb database inside registration table created as you can see in the below image.


2) Create connection.php page


$hostname = "localhost";

$username = "root";

$password = "";

$database = "sampledb";

$conn = mysql_connect("$hostname","$username","$password") or die(mysql_error());

mysql_select_db("$database", $conn) or die(mysql_error());



3) Create index.php page

<form action="upload.php" method="post" enctype="multipart/form-data">

File Upload &nbsp;<input type="hidden" name="MAX_FILE_SIZE" value="10000000000" placeholder="Upload Report Here"/><input name="file" type="file" />

<input type="submit" onclick="myFunction()" value="Submit" style="height:35px; width:65px; "/></form>


4) Create upload.php page


include ("connection.php");

$file = $_FILES['file']['tmp_name'];

$handle = fopen($file, "r");

$c = 0;

while(($filesop = fgetcsv($handle, 1000, ",")) !== false)


$name= $filesop[0];

$username= $filesop[1];

$password= $filesop[2];

$mobile= $filesop[3];

$sql = mysql_query("INSERT INTO registration(name, username, password, mobile) VALUES ('$name', '$username', '$password', '$mobile')");

$c = $c + 1;



echo "You database has imported successfully. You have inserted ". $c ." recoreds";



echo "Sorry! There is some problem.";







Support us by Sharing