I tried to upload around 20k rows CSV into SQL using async method referring to this post :
How to import a huge CSV file with 200,00 rows to MySQL (asynchronous and fast)?
The script already running and success when I upload 10000 data, but when I checked into the database, I found that only half rows (5000 rows) were Inserted. I've tried to change the $batchsize from 1000 to 100, only 9400rows inserted instead of supposedly 10000 rows
here's my current code :
index.php :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>csv upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" />
</form>
</body>
</html>
upload.php :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script>
//Declaration of function that will insert data into database
function senddata(filename){
var file = filename;
$.ajax({
type: "POST",
url: "senddata.php",
data: {file},
async: true,
success: function(html){
$("#result").html(html);
}
})
}
</script>
<?php
$batchsize = 100; //split huge CSV file by 1,000, you can modify this based on your needs
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = explode(".", $name);
$ext = $ext[1];
$tmpName = $_FILES['csv']['tmp_name'];
if($ext === 'csv'){ //check if uploaded file is of CSV format
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle)) !== FALSE) {
//splitting of CSV file :
if ($row % $batchsize == 0):
$file = fopen("minpoints$row.csv","w");
endif;
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
$min = $data[0];
$points = $data[1];
$json = "'$min', '$points'";
fwrite($file,$json.PHP_EOL);
//sending the splitted CSV files, batch by batch...
if ($row % $batchsize == 0):
echo "<script> senddata('minpoints$row.csv'); </script>";
endif;
$row++;
}
fclose($file);
fclose($handle);
}
} else {
echo "Only CSV files are allowed.";
}
//alert once done.
echo "<script> alert('CSV imported!') </script>";
} ?>
senddata.php :
<?php
include('config.php');
$data = $_POST['file'];
$handle = fopen($data, "r");
$test = file_get_contents($data);
// print_r($test);die;
if ($handle) {
$counter = 0;
//instead of executing query one by one,
//let us prepare 1 SQL query that will insert all values from the batch
$sql ="INSERT INTO table_test(name,contact_number) VALUES ";
while (($line = fgets($handle)) !== false) {
$sql .= "($line),";
$counter++;
}
$sql = substr($sql, 0, strlen($sql) - 1);
if ($conn->query($sql) === TRUE) {
} else {
}
fclose($handle);
} else {
}
//unlink CSV file once already imported to DB to clear directory
unlink($data);
?>
My Goals are :
- Upload huge csv data asynchronusly with complete data
- To understand this codes : --> fwrite($file,$json.PHP_EOL); and --> senddata('minpoints$row.csv'); ;