How to import CSV in PHP MySQL

fgetcsv() method is used to read data from CSV file. First create an excel sheet and save it as .csv format

Here you can download CSV.

Example to import CSV file and save to database.


<html>
 <body>
<form method="post" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border="0" id="ad_tab">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="req">File name to import : </td>

<td><input type="file" name="filename" size="50"></td>
</tr>
<tr>
<td>
<input type="submit" value="Upload" name="submit"></td>
<tr>
</table>
</form>
</body>
</html>

submit.php

if(isset($_POST['submit'])) {
$data=$_FILES['filename'];
if(!$data['size'])
$err="please select the file";
elseif(is_uploaded_file($_FILES['filename']['tmp_name'])){
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$csvData="Name,Email,Address,Hobby,Country,Mobile,Course\n";
$hasNext=1;
$i=date('Ymdhis',time());
$fileName="error".$i.".csv";
$fh=fopen($fileName,"a+");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
IF($data[0]==""||$data[1]==""||$data[2]==""||$data[3]==""||$data[4]==""||$data[5]==""||$data[6]==""){
$csvData.=$data[0].",".$data[1].",".$data[2].",".$data[3].",".$data[4].",".$data[5].",".$data[6]."\n";

}
else{
if($hasNext) {
$import="INSERT into infomation
(name,email,address,hobby,country,mobile,course) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
mysql_query($import);
}
}
$hasNext++;
}
$err="Import Done";
fwrite($fh,$csvData);
fclose($fh);
}
} 

Leave a Reply