I know how to export to CSV using PHP to query mySQL and populate the CSV. However, is it possible to have the users select what columns they would like to have and vary the SQL query accordingly?
I have established the connection to the database, added my query which is:
$query = sprintf("SELECT x, y, z from a");
$result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=export.csv' );
$row = mysql_fetch_assoc( $result );
if ( $row )
{
echocsv( array_keys( $row ) );
}
while ( $row )
{
echocsv( $row );
$row = mysql_fetch_assoc( $result );
}
function echocsv( $fields )
{
$separator = '';
foreach ( $fields as $field )
{
if ( preg_match( '/\\r|\\n|,|"/', $field ) )
{
$field = '"' . str_replace( '"', '""', $field ) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}