Hi guys, now in this post I am discussing how to import csv file into MySql database.
Its very common task for every application which has too much database and need to import in MySql.Normally when we need to import data into database then we used following terminology.
1-Xml
2-CSV file
3-Excel file
Today we are discussing to import data throgh CSV file into MySql Database.
Our PHP code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
<?php
if(isset($_POST["submit"]))
{
$host="localhost"; // Host name.
$db_user="root"; //mysql user
$db_password=""; //mysql pass
$db='phpDB'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
echo $filename=$_FILES["file"]["name"];
$ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));
//we check,file must be have csv extention
if($ext=="csv")
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT into tableName(name,email,address) values('$emapData[0]','$emapData[1]','$emapData[2]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported.";
}
else {
echo "Error: Please Upload only CSV File";
}
}
?>
Below code is used for creating interface to upload CSV file.
HTML UI code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<form enctype="multipart/form-data" method="post"> <table border="1"> <tr > <td colspan="2" align="center"><strong>Import CSV file</strong></td> </tr> <tr> <td align="center">CSV File:</td><td><input type="file" name="file" id="file"></td></tr> <tr > <td colspan="2" align="center"><input type="submit" value="submit"></td> </tr> </table> </form>