ad

How To Import CSV File In MySQL Database With PHP

Sometimes in a web application there is a need to upload bulk data to MYSQL by using excel sheets. This helps website owner to upload records easily. Handling the file upload with excel sheets and then add it to the database is easy. You can do it with some easy file handling in PHP. PHP has built in functions to handle CSV files and read the record from it.

See the sample code below. Change the connection strings according to your code.

How To Import or Upload CSV File In MySQL Database With PHP

<?php
mysql_connect('localhost','root','');
mysql_select_db('database');
if(isset($_POST['submit']))
{
$fname = $_FILES['file']['name'];

$chk_ext = explode(".",$fname);
echo($fname);
echo($chk_ext);
echo($chk_ext[1]);
if(strtolower($chk_ext[1]) == "csv")
{

$filename = $_FILES['file']['tmp_name'];
$handle = fopen($filename, "r");
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($i>0)
{
$sql = "insert into table (col1, col2) values('$data[0]','$data[1]')"; // use according to the csv and table
mysql_query($sql) or die(mysql_error());
}
$i++;
}

fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">

Import File : <input type='file' name='file' size='20' />
<input type='submit' name='submit' value='submit' />
</form>&nbsp;

Change database connection and SQL query as per your own need.

In case, you are facing any problem in implementing the code, you can comment below for help.

Nord VPN Sale

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Developed By Deepanker