Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. // config.php
  2. <?php
  3. //connections here
  4. $servername = "localhost";
  5. $username = "root";
  6. $password = "";
  7. $dbname = "Software";
  8. $conn = new mysqli($servername, $username, $password, $dbname);
  9. if ($conn->connect_error) {
  10. die("Connection failed: " . $conn->connect_error);
  11. } ?>
  12.  
  13. <form action="upload.php" method="post" enctype="multipart/form-data">
  14. <input type="file" name="csv" value="" />
  15. <input type="submit" name="submit" value="Save" />
  16. </form>
  17.  
  18. <?php
  19. $csv = array();
  20. $batchsize = 10000; //split huge CSV file by 1,000
  21. if($_FILES['csv']['error'] == 0){
  22. $name = $_FILES['csv']['name'];
  23. $value = explode('.', $_FILES['csv']['name']);
  24. $ext = strtolower(end($value));
  25. $tmpName = $_FILES['csv']['tmp_name'];
  26. if($ext === 'csv'){ //check if uploaded file is of CSV format
  27. if(($handle = fopen($tmpName, 'r')) !== FALSE) {
  28. set_time_limit(0);
  29. $row = 0;
  30. while(($data = fgetcsv($handle)) !== FALSE) {
  31. $col_count = count($data);
  32. //splitting of CSV file :
  33. if ($row % $batchsize == 0):
  34. $file = fopen("minpoints$row.csv","w");
  35. endif;
  36. $csv[$row]['col1'] = $data[0];
  37. $csv[$row]['col2'] = $data[1];
  38. $min = $data[0];
  39. $points = $data[1];
  40. $json = "'$min', '$points'";
  41. fwrite($file,$json.PHP_EOL);
  42. //sending the splitted CSV files, batch by batch...
  43. if ($row % $batchsize == 0):
  44. echo "<script> senddata('minpoints$row.csv'); </script>";
  45. endif;
  46. $row++;
  47. }
  48. fclose($file);
  49. fclose($handle);
  50. }
  51. }
  52. else
  53. {
  54. echo "Only CSV files are allowed.";
  55. }
  56. //alert once done.
  57. echo "<script> alert('CSV imported!') </script>";
  58. }
  59. ?>
  60.  
  61. <?php
  62. include('config.php');
  63. $data = $_POST['file'];
  64. $handle = fopen($data, "r");
  65. $test = file_get_contents($data);
  66. if ($handle) {
  67. $counter = 0;
  68. //instead of executing query one by one,
  69. //1 SQL query that will insert all values from the batch
  70. $sql ="INSERT INTO table_test(phone_number,first_name,last_name,address,city,state,zipcode) VALUES ";
  71. while (($line = fgets($handle)) !== false) {
  72. $sql .= "($line),";
  73. $counter++;
  74. }
  75. $sql = substr($sql, 0, strlen($sql) - 1);
  76. if ($conn->query($sql) === TRUE) {
  77. } else {
  78. }
  79. fclose($handle);
  80. } else {
  81. }
  82. //unlink CSV file once already imported to DB to clear directory
  83. unlink($data);
  84. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement