3/29/2017 - 9:16 PM

Export MySQL table to CSV with button

Export MySQL table to CSV with button


<a  href="http://example.com/admin/export.php" class="btn btn-warning">Export CSV</a>

// require DB config + constants
require "../config/dbconfig.php";  	  	

try {
	$pdo = new PDO($dsn, $username, $password);
	//echo "connected to DB<br>";
	//Create our SQL query.
	$sql = "SELECT * FROM Quotes";
	//Prepare our SQL query.
	$statement = $pdo->prepare($sql);

	$statement->execute() or die(print_r( $statement->errorInfo(), true) );
	//Fetch all of the rows from our MySQL table.
	$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
	//Get the column names.
	$columnNames = array();
	    //We only need to loop through the first row of our result
	    //in order to collate the column names.
	    $firstRow = $rows[0];
	    foreach($firstRow as $colName => $val){
	        $columnNames[] = $colName;
	//Setup the filename that our CSV will have when it is downloaded.
	$fileName = 'quotes_export.csv';
	//Set the Content-Type and Content-Disposition headers to force the download.
	header('Content-Type: application/excel');
	header('Content-Disposition: attachment; filename="' . $fileName . '"');
	//Open up a file pointer
	$fp = fopen('php://output', 'w');
	//Start off by writing the column names to the file.
	fputcsv($fp, $columnNames);
	//Then, loop through the rows and write them to the CSV file.
	foreach ($rows as $row) {
	    fputcsv($fp, $row);
	//Close the file pointer.
} catch (PDOException $e) {
	// print trace
    $error_message = $e->getMessage();