Import CSV File Into MySQL Using PHP

 Learn How to Import CSV File into MySQL Database Using PHP

 

 

This article shows you how to import an uploaded CSV file into MySQL using PHP.

index.php file having a form code to upload a CSV file. Once the file uploaded successfully, PHP opens it and reads the line from CSV. Each line of data separated into php variables and then inserted into MySQL table. This process continues until the last line of the CSV. Once it is finished inserting, It displays a message – "Data Inserted in database" And finally closes CSV file. In case any error in uploading, it shows "the file type not allowed" message. PHP Version 5.5.11


1. Create a table with given code in a Database.

Query:

CREATE TABLE IF NOT EXISTS `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) DEFAULT NULL,
  `description` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

 


2. Create a following file with you database details and include it in a index.php

 db_config.php

<?php

$databaseHost = 'localhost';
$databaseuser = 'root';
$databasePassword = '';
$databaseName = 'sampledb';

$conn = mysqli_connect($databaseHost, $databaseuser, $databasePassword, $databaseName); 
 
?>

 

3. Open notepad and copy the given text and save it as sample.csv. 

sample.csv

id,title,description
1,product1,description1
2,product2,description2
3,product3,description3
4,product4,description4
5,product5,description5

 

4. Now start the server and open the index file and upload the sample.csv. 


index.php

<?php 

require('db_config.php');

if(isset($_POST["submit"]))

{
 
$mimes =  
array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
 
 
if(in_array($_FILES["file"]["type"],$mimes)){


$file =    $_FILES["file"]["tmp_name"];
 
$count = 0;

$file_open = fopen($file, "r");
 
while (!feof($file_open))
{
	 
	$csv = fgetcsv($file_open, 1000);
	
	$count++;
	
	$id = $csv[0];
	$title = $csv[1];
	$description = $csv[2]; 
	
	if($count == 1)   continue; //skips inserting titles. 
	 
$query = "insert into items(title,description) values('".$title."','".$description."')";
	
	$result = mysqli_query($conn,$query);
}
 
echo "<br />Data Inserted in dababase";

fclose($file_open); 
 
}
 
else { 
 
die("<br/>Sorry, File type Error. Only CSV file allowed."); 
 
}

mysqli_close($conn); 
 
}

?>
 
<html>
 
<head>

<title>coding-zon tutorials Demo:
Import CSV File Into MySQL Using PHP  
 
</title>  
 
</head> 
 
<body>
 
<div id="wrapper">
 
<form method="post" action="" enctype="multipart/form-data"> 
 
 <input type="file" name="file"/>
 <input type="submit" name="submit" value="Upload File"/>
 
</form>
 
</div>
 
</body>
</html>
 
  
 
 
 Demo:
 
 

 
 
 
 
 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP