Selasa, 22 Juli 2014

Import CSV Data File ke MySql dengan PHP (File Upload dari PC User)

Menganggapi dari komentar saudara solikin pada Import CSV Data File ke MySql dengan PHP maka saya mencoba menata kembali script tersebut.


Pertama kita buat form upload sederhana.
<html>
<body>
<form action="proses.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html> 

Kita beri nama upload_csv.php kemudian untuk proses.php sebagai berikut:

<?php
//proses upload
$allowedExts = array("csv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if (($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
     
 //koneksi database
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//nama database
$cid =mysql_select_db('databaseku',$connect);

//tempat file csv berada
define('CSV_PATH','C:/wamp/www/folderku/upload/');

$csv_file = CSV_PATH . $_FILES["file"]["name"];

if (($getfile = fopen($csv_file, "r")) !== FALSE) {
         $data = fgetcsv($getfile, 1000, ",");
    while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
       $num = count($data);
        for ($c=0; $c < $num; $c++) {
            $result = $data;
        $str = implode(",", $result);
        $slice = explode(",", $str);
       
                        $col1 = $slice[0];
                        $col2 = $slice[1];
                        $col3 = $slice[2];
// SQL Query untuk insert data
$query = "INSERT INTO data_pribadi(no,nama,alamat)
VALUES('".$col1."','".$col2."','".$col3."')";

$s=mysql_query($query, $connect );

        }
    }
}
echo "file csv berhasil di import ke database!!";
mysql_close($connect);
     
    }
  }
} else {
  echo "Invalid file";
}
?> 


Selamat Mencoba dan Terima Kasih
Categories: , , ,

0 comments:

Posting Komentar

Subscribe to RSS Feed Follow me on Twitter!