Transfer Data Text ke MySQL

Untuk melengkapi koleksi skrip PHP berikut ini adalah skrip yang berguna untuk mentransfer data yang ada di file text (.txt) ke database MySQL.

Skrip PHP ini terdiri dari 3 file PHP dan 1 file txt sebagai sample:

1. config.php -> file PHP berisi konfigurasi database.

2. fileClass.php -> file berisi function utama

3. Exe.php -> contoh file PHP yang harus di eksekusi melalui browser.

4. Sample.txt -> contoh file text yang akan di transfer isinya ke tabel MySQL

config.php

<?

$host="localhost";
$user_name="username";
$password="password";
$db="databasename";

define("DB",$db);
define("HOST",$host);
define("USERNAME",$user_name);
define("PASSWORD",$password);
?>

fileClass.php

<?
lass exportFile
{
var $Query_ID=0;
var $connection=0;

function connect()
{
if($this->connection==0) {
$this->connection=mysql_connect(HOST,USERNAME,PASSWORD) or die("<b>Database Error</b><br>".mysql_error());
$SelectResult = mysql_select_db(DB, $this->connection) or die("Couldnot Select Database".mysql_error());
} else {
echo "Connection Couldnot be Established";
die();
}
}

function query($sql) {
$this->Query_ID=mysql_query($sql,$this->connection);
if(!$this->Query_ID) {
echo "Query Failed".mysql_error();
} else {
return $this->Query_ID;
}
}

function exportFileToDatbase($filename,$de,$mode,$tablename,$column1,$column2,$fieldno)
{
//$sqltrunk = "TRUNCATE TABLE $tablename";
//$this->query($sqltrunk);
$fd=fopen($filename,"$mode");
while(!feof($fd)) {
$line=fgets($fd,5000);
$f=explode($de,$line);
for($i=0;$i<$fieldno;$i++) {
$a[]=trim("'$f[$i]'");
}
$value=implode(",",$a);
unset($a);
$sql="insert into $tablename ($column1,$column2) values($value)";
//echo $sql;
$this->query($sql);

}

}

}

?>

sample.txt

Paijo:0811
Jono:0812
Bejo:0813

Exe.php

<?
include("config.php");
include("fileClass.php");
$objFile=new exportFile;
$objFile->connect();
$objFile->exportFileToDatbase("sample.txt",":","r","user","nama","nohp",2);  //nama file, tanda pemisah, mode, nama tabel, kolom1, kolom2, jumlah field

echo "Transfer data sukses :-*";
?>

Upload semua file tersebut diatas dalam satu folder ke web server, lalu jalankan file Exe.php.

Source Code by : Suraj Thapaliya

Wow. It's Quiet Here...

Be the first to start the conversation!

Leave a Reply:

Gravatar Image

Follow

Get every new post on this blog delivered to your Inbox.

Or subscribe to the RSS feed by clicking on the counter: