Import csv file in mysql using php


This tutorial will go over how to import CSV ( comma separated value ) file data into Mysql Database using Php . 

CSV file is should be like below



<!-- form to submit csv file -->
<form enctype="multipart/form-data" method="post" role="form">
    <div class="form-group">
        <label for="exampleInputFile">File Upload</label>
        <input type="file" name="file" id="file" size="150">
        <p class="help-block">Only CSV File Import.</p>
    </div>
    <button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>


//php code to process csv file and store data into mysql database
<?php
if(isset($_POST["Import"]))
{
    //First we need to make a connection with the database
    $host='localhost'; // Host Name.
    $db_user= ''; //DB User Name
    $db_password= '';  //DB Password
    $db= ''; // Database Name.

    //Create connection with databse
    $conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
    mysql_select_db($db) or die (mysql_error());
    echo $filename=$_FILES["file"]["tmp_name"];

    if($_FILES["file"]["size"] > 0)
    {
        $file = fopen($filename, "r");
$count = 0;
        while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
        {
$count++;
                        // ignore first row for column names
if($count>1)
{
                                //insert into database
$sql = "INSERT into demo1(id,name) values ('$emapData[0]','$emapData[1]')";
mysql_query($sql);
}
        }
        fclose($file);
        echo 'CSV File has been successfully Imported';
    }
    else
        echo 'Invalid File:Please Upload CSV File';
}
?>

0 comments :