Home > PHP SCript > cara mengambil isi file csv dengan php serta membuat query MYSQL nya

cara mengambil isi file csv dengan php serta membuat query MYSQL nya

Berikut cara untuk mengambil isi file csv dengan php dan membuat query untuk memasukkan isinya ke database mysql.
baris pertama tabel bisa langsung dibuat query create table.

<?php
echo ‘<html>’;
echo ‘<style type=”text/css”>’;
echo ‘
.tbl {
border-collapse:collapse;
}
.tbl td {
border:1px solid #000000;
}
‘;
echo ‘</style>’;

echo ‘<body><table>’;

//jika nama file : namaFileCSV.csv
$tabel = ‘namaFileCSV’;//tanpa ekstensi
$f = fopen(“$tabel.csv”, “r”);
$no = 0;
$oke = 0;
while (($line = fgetcsv($f)) !== false) {
$no++;

if ($no>0 AND $no<=100) {

$sql = ‘ insert into ‘.strtolower($tabel).’ values (‘;
foreach ($line as $cell) {
$sql .= ‘\”.htmlFormat($cell).’\’,’;
}
$sql .= ‘\”.time().’\’)’;
if (mysql_query($sql)) {
$oke++;
$tmpl = $oke;
}else{
$tmpl = $sql;
}

echo ‘<tr>’;
echo ‘<td>’ .$no. ‘</td>’;

echo ‘<td>’.$tmpl.'</td>’;
echo ‘</tr>’;
}

if ($no==1) {

echo ‘<tr>’;
echo ‘<td>’ .$no. ‘</td>’;

echo ‘<td>’;
echo ‘
CREATE TABLE ‘.$tabel.’ (
‘;
foreach ($line as $cell) {
echo htmlspecialchars($cell).’ VARCHAR( 100 ) NOT NULL, <br />’;

}
echo ‘
`tanggal_masuk` INT(11) NOT NULL
) ENGINE = MYISAM ;
‘;
echo ‘</td>’;

echo ‘<tr>’;

}
}
fclose($f);

echo ‘</table></body></html>’;
?>

Categories: PHP SCript Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: