I have a table in database with fields (Id,Name,Email,Employee Code,Joining Date,Address) and i have a csv file which containing same fields. I have to import csv file into database with same header. If header is different then it should not import into database and throw an error. I have to check while uploading csv into database, if any value(email or Employee code) is already in the database then it should ignore the field and throw an error. Please help .
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="password";
$db='testcsv'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
$fieldinfo=array();
echo $filename=$_FILES["file"]["tmp_name"];
$query="SELECT * FROM csv";
$output=mysql_query($conn,$query);
while ($fieldinfo=mysqli_fetch_field($output))
{
$columns=$fieldinfo;
}
echo $query;
echo "<br/>";
print_r($output);
echo "<br/>";
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$header = fgetcsv($file);
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$record = array_combine($header, $emapData);
echo "<br>";
echo $record;
echo "<br>";
$sql = "INSERT into csv(Name,Email,EmployeeCode,JoiningDate,Address) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>
<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>