Ekspor SQL to CSV – PHP

Ekspor SQL to CSV – PHP

Ekspor data dari SQL ke CSV menggunakan PHP. Untuk melakukan ekspor file dari SQL ke CSV kali ini dilakukan tanpa menggunakan plugin, artinya hanya membutuhkan perintah Header agar browser dapat mengenali file tersebut. Cara ini merupakan alternatif bagi teman-teman yang ingin melakukan ekspor file dengan metode yang cukup sederhana.

Tahap uji coba teman-teman bisa membuat file index.php, koneksi.php, dan exp.php

File index.php

<!DOCTYPE html>
<html>
<head>
	<title>SQL to CSV - PHP</title>
</head>
<body>

	<h3>SQL to CSV dengan PHP</h3>

	<table border="1">
		<thead>
			<tr>
				<th>No</th>
				<th>ID</th>
				<th>Nama</th>
				<th>Email</th>
				<th>Jurusan</th>
			</tr>
		</thead>
		<tbody>
			<?php
				include "koneksi.php";

				$no = 1;

				$sql = "SELECT * FROM tbl_pegawai ORDER BY id DESC";
				$query = mysqli_query($konek,$sql) or die (mysqli_error($konek));
				
				while($data = mysqli_fetch_array($query)){?>
					<tr>
						<td><?php echo $no; ?></td>
						<td><?php echo $data['id'];?></td>
						<td><?php echo $data['nama'];?></td>
						<td><?php echo $data['email'];?></td>
						<td><?php echo $data['jurusan'];?></td>
					</tr>
					
					<?php $no++; ?>

				<?php }
			?>
			
		</tbody>
	</table>

	<form action="exp.php" method="post">
		<input type="submit" name="export" value="Export">
	</form>

</body>
</html>

File exp.php

<?php
	include "koneksi.php";

	if(isset($_POST["export"])){
		header('Content-Type: text/csv; charset=utf-8');
		header('Content-Disposition: attachment; filename=data.csv');
		$output = fopen("php://output", "w");
		fputcsv($output, array('ID','Nama','Email','Jurusan'));
		$sql = "SELECT * FROM tbl_pegawai";
		$query = mysqli_query($konek,$sql) or die (mysqli_error($konek));
		while($data = mysqli_fetch_assoc($query)){
			fputcsv($output, $data);
		}
		fclose($output);
	}
?>

File koneksi.php

<?php
	$server = "localhost";
	$user = "root";
	$pass = "";
	$database = "csvku";

	$konek = mysqli_connect($server,$user,$pass,$database) or die (mysqli_error());
	
?>

Untuk file koneksi sesuaikan dengan database yang kalian gunakan.

Demonya bisa teman-teman lihat disini:
DEMO