Skip to content

Instantly share code, notes, and snippets.

@greg-randall
Created February 15, 2024 22:16
Show Gist options
  • Save greg-randall/b57f7f6b2dd1db2dc9e64fd2ebdde775 to your computer and use it in GitHub Desktop.
Save greg-randall/b57f7f6b2dd1db2dc9e64fd2ebdde775 to your computer and use it in GitHub Desktop.
Database table to CSV dumper. Add info at the top to connect to your database/table etc.
<?php
// Dumps a database table out to the screen or out a csv file.
// add ?download=true to the url to download the file
// Database credentials, table, filename, and timezone
$db_host = "";
$db_user = "";
$db_pass = "";
$db_name = "";
$db_table = "";
$output_filename = "";
date_default_timezone_set( 'America/Chicago' );
// Set to true to show the first five rows of the CSV file
$debug = false;
// Check for a download request
if ( isset( $_GET[ 'download' ] ) ) {
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment; filename="' . $output_filename . '_' . date( "m-d-Y_h-ia" ) . '.csv"' );
$download = true;
} else {
echo "<pre>";
$download = false;
}
// Create a new mysqli object
$mysqli = new mysqli( $db_host, $db_user, $db_pass, $db_name );
// Check for any connection errors
if ( $mysqli->connect_error ) {
die( 'Error : (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error );
}
// Set the SQL query
if ( !$debug ) {
$query = "SELECT * FROM $db_table";
} else {
$query = "SELECT * FROM $db_table LIMIT 5";
}
// Execute the query
$result = $mysqli->query( $query );
// Build the output array
$key_count = 0;
while ( $row = $result->fetch_assoc() ) {
foreach ( $row as $key => $value ) {
$output[ $key_count ][ $key ] = str_replace( array(
"\n",
"\r"
), array(
"\\n",
"\\r"
), htmlspecialchars( $value, ENT_QUOTES, 'UTF-8', false ) );
}
$key_count++;
}
// Open a file handle to php://output
$file = fopen( 'php://output', 'w' );
// Write the heading
fputcsv( $file, array_keys( $output[ 0 ] ) );
// Write the data
foreach ( $output as $row ) {
fputcsv( $file, $row );
}
// Close the file
fclose( $file );
if ( !$download ) {
echo "<pre>";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment