31 December 2015

Import file txt ke Database MySQL

File text yang akan di import menggunakan delimiter penghubung ; (titik koma), tampilannya seperti berikut ini :

10032;Sukarno, Mohamad;PHP & Jason Developer's Guide;Computer;57500;2015-03-18;An in-depth look at creating applications with PHP & Jason.

10033;Brain, Mathew;ASP .NET Developer's Guide;Computer;60500;2015-08-15;An in-depth look at creating applications with ASP .NET.

10034;Bro, Man;JSP Developer's Guide;Computer;60500;2015-04-24;An in-depth look at creating applications with JSP


dbkoneksi.php

<?php
$host = "localhost";

$user = "root";
$pass = "";
$dtbase = "blog";
$ceka = mysqli_connect($host,$user,$pass,$dtbase) or Die("Tidak terkoneksi ke server");

?>


importtxt.php


<form method='post' enctype='multipart/form-data'>
Silakan Pilih File hidden: <input name='userfile' type='file' class='form-control'><br>
<input name='upload' type='submit' value='Import' class='btn btn-danger'>
</form>
<form method='post'>
<?php
if(!empty($_POST['upload'])) {
$nm_file = $_FILES['userfile']['name'];
$tp_file = $_FILES['userfile']['tmp_name'];
$fp = fopen($nm_file, "r");
$i=1;
while ($line = fgets($fp)) { // Loop through each line
     list ($id, $author, $title, $genre, $price, $publish_date, $description) = split(";", $line, 7); // Split the line by ; delimiter and store it in our list
                 echo "$i. $id, $author, $title, $genre, $price, $publish_date, $description
                 <input type=hidden name=id$i value='$id'>
                 <input type=hidden name=author$i value='$author'>
                 <input type=hidden name=title$i value='$title'>
                 <input type=hidden name=genre$i value='$genre'>
                 <input type=hidden name=price$i value='$price'>
                 <input type=text name=publish_date$i value='$publish_date'>
                 <input type=hidden name=description$i value='$description'><br>";
                 $i++;
}
$n=100;
if($i<$n) { $maks = $i-1; }
echo "<input type=hidden name=total value=$maks><br><input type=submit name=proses value='PROSES AKHIR'>";

}
?>
</form>
<?php
include("dbkoneksi.php");
if(!empty($_POST['proses'])) {
for($i=1;$i<=$_POST['total'];$i++) {
$id[$i] = $_POST["id$i"];
$author[$i] = $_POST["author$i"];
$title[$i] = $_POST["title$i"];
$genre[$i] = $_POST["genre$i"];
$price[$i] = $_POST["price$i"];
$publish_date[$i] = $_POST["publish_date$i"];
$description[$i] = addslashes($_POST["description$i"]);
$sql = "insert into book (id,author,title,genre,price,publish_date,description)
values ('$id[$i]', '$author[$i]', '$title[$i]', '$genre[$i]', '$price[$i]', '$publish_date[$i]', '$description[$i]')"; // Generate our sql string
mysqli_query($ceka,$sql); // Execute the sql               
}
echo "<script>alert('Data berhasil di import !');</script>";
}
?>





No comments:

Post a Comment