<?php
session_start();
  if(empty($_SESSION))
  {
    header("Location: ../login");
  }
else
{
    include "../../assets/config/koneksi.php";
    // unggah csv
    if (isset($_POST['submit'])) {//Script akan berjalan jika di tekan tombol submit..


//Script Upload File..
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." Berhasil di Upload" . "</h1>";
        echo "<h2>Menampilkan Hasil Upload:</h2>";
        readfile($_FILES['filename']['tmp_name']);
    }
    $handle = fopen($_FILES['filename']['tmp_name'], "r");
	$cek  = fgetcsv($handle,0,','); //baca isi csv perbaris dengan koma
		if(!empty($cek[1])) { 
			$delimiter=",";
		}
		else { 
			$delimiter=";";
			 }
fclose($handle);

    //Import uploaded file to Database, Letakan dibawah sini..

    $handle = fopen($_FILES['filename']['tmp_name'], "r");
	$baris= 0;
while(!feof($handle)) //cari akhir baris csv
{
  $data = fgetcsv($handle,0,$delimiter);
  if(!empty($data[0])) //tidak mengikutkan spasi kosong
  { 
  if($baris >= 1) //karena baris 0 adalah judul kolom/field
  {

$id   = $data[0];
$gambar = $data[1];
$nis  = $data[2];
$nama = $data[3];
$tmp_lahir  = $data[4];
$tgl_lahir   = $data[5];
$jk = $data[6];
$alamat  = $data[7];
$id_prov = $data[8];
$id_kab  = $data[9];
$id_kec   = $data[10];
$id_kel = $data[11];
$username  = $data[12];
$password  = $data[13];
$id_level = $data[14];
$hp  = $data[15];
$email   = $data[16];
$sql = "INSERT INTO user 
   (id, gambar, nis, nama, tmp_lahir, tgl_lahir, jk, alamat, id_prov, id_kab, id_kec, id_kel, username, password, id_level, hp, email) 
   VALUES 
   ('$id', '$gambar', '$nis', '$nama', '$tmp_lahir', '$tgl_lahir', '$jk', '$alamat', '$id_prov', '$id_kab', '$id_kec', '$id_kel', '$username', '$password', '$id_level', '$hp', '$email')";
mysqli_query($koneksi,$sql);

  } 
  }
$baris++;
}
    fclose($handle); //Menutup CSV file
    echo "<script>window.alert('Data Berhasil di Upload!');
                window.location='../view-datacsv'</script>";

}
}

?>

