how to import csv file to database

 Uploading a csv data file using php and writes the data to mysql database.


<?php
$target_dir = "vcode/";  $ids=uniqid();
                $target_file = $target_dir.$date1.$ids.basename($_FILES["file1"]["name"]); $uploadOk = 1;
                $file_size = $_FILES["file1"]["size"];
                $ext = pathinfo($_FILES["file1"]["name"], PATHINFO_EXTENSION);
                if( $ext !== 'csv' )
                {
                    die("Error: Please select a valid file format.");
                }
                // Verify file size - 2MB max
                $maxsize = 2 * 1024 * 1024;
                if ($file_size > $maxsize)
                {
                    die("Error: File size is larger than the allowed limit.");
                }                    
                if ($ext=='csv' and $file_size<=$maxsize)
                {
                     if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file))
                     {
                          //echo "The file ".  $_FILES["file1"]["name"]." has been uploaded.";
                          // inserting to database
                          $fp = fopen($target_file, "r");
                          while( !feof($fp) )
                          {
                              if( !$line = fgetcsv($fp, 1000, ';', '"'))
                              {
                                 continue;
                              }
                          $query_upload = "insert into tablename(tbl_voucher_id, voucher_code) values('$tbl_voucher_id', '$line[0]')";
                          $result_upload = mysqli_query($conn, $query_upload) or die(mysqli_error($conn));
                          //echo $target_file.$importSQL."<br>";
                            }
                      }
                      fclose($fp);
                      // inserting to database
                 }  
                 else
                  {
                        echo "Sorry, there was an error uploading your file.";
                  }
?>                  

Comments