<?php
die('Invailid Url');
set_time_limit(0);
ini_set('memory_limit','1024M');
ini_set('post_max_size','32M');
ini_set('upload_max_filesize ','32M');

$destdir  = "live-data-migration-csvs/";
$name     = "country_code.csv";
$destfile = $destdir.$name;  

$batch_size = 3000;
$table_name = "country";
$records_inserted = 0;
$records_updated = 0;  
                                   
$flag = true;
$fp = fopen($destfile, 'r');
while (!feof ($fp)){
  $buffer = fgetcsv($fp, 1000000, ',');  
  if($flag) { 
	  if($buffer){ 
	  
	        $variable_array = array("country","country_code");
			foreach($variable_array as $key=>$val){		
				${$val} = addslashes(trim($buffer[$key]));
			}
			if($country =="country"){
				continue;
			}
						
			
			$created_by					= $_SESSION['user_id'];
			$created_on					= date("Y-m-d H:i:s");	
			$updated_by					= $_SESSION['user_id'];
			$coun_qry = "SELECT id FROM $table_name WHERE country = '$country'";
			$coun_sql = mysqli_query($conn,$coun_qry);
			$country_exist_id = "";
			if(mysqli_num_rows($coun_sql)>0){
				$data1 = mysqli_fetch_array($coun_sql);
				$country_exist_id = $data1['id'];
				
				$sql_update = "country = '".$country."',country_code = '".$country_code."', updated_by = '".$updated_by."' ";
				$sql_update = "UPDATE $table_name SET ".$sql_update." WHERE id = '".$country_exist_id."'";
				if(mysqli_query($conn,$sql_update)){
					$records_updated++;
				}					
			}else{				
				$sql = "country = '".$country."', country_code = '".$country_code."', created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."' ";
				$sql= "INSERT INTO $table_name SET ".$sql;
				
				if(mysqli_query($conn,$sql)){
					$records_inserted++;
				}
			}
	  }
  }
}
?>
<?php 
if($records_inserted){    
  echo '<br><span style="font-family:calibri;color:red;">'.($records_inserted).' records has been inserted...</span>';
}?>
 <?php 
if($records_updated){    
  echo '<br><span style="font-family:calibri;color:red;">'.($records_updated).' records has been updated...</span>';
}?>