Skip to content

Instantly share code, notes, and snippets.

@imelgrat
Last active October 27, 2022 14:49
Show Gist options
  • Save imelgrat/8a18c430e9aa932deeec to your computer and use it in GitHub Desktop.
Save imelgrat/8a18c430e9aa932deeec to your computer and use it in GitHub Desktop.
CSV export of a MySQL query using a PHP class. Full article and function source at: http://imelgrat.me/php/csv-exports-using-php-class
<?php
#Include the class. This class takes the results of a SQL query and outputs in the CSV (comma separated values) format.
require_once("iam_csvdump.php");
# Set the parameters: SQL Query, hostname, databasename, dbuser and password
$dumpfile = new iam_csvdump;
# Call the CSV Dumping function and THAT'S IT!!!! A file named export.csv is sent to the user for download
$dumpfile->dump("SELECT * FROM `tablename`", "export", "csv", "mysql", "root", "", "localhost" );
?>
<?php
#Include the class. This class takes the results of a SQL query and outputs in the CSV (comma separated values) format.
require_once("iam_csvdump.php");
# Set the parameters: SQL Query, hostname, databasename, dbuser and password
$dumpfile = new iam_csvdump;
# Call the CSV Dumping function with empty filenames and extension to send the query results to the browser as raw text
$dumpfile->dump("SELECT * FROM user", "", "", "mysql", "root", "", "localhost" );
?>
@sebastiano75
Copy link

Hi, great work
How can I use it with PostgreSql? There is a way to give port 5432 as param?
I'm trying but I receive an http 500 error...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment