Reputation: 97
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";
}
Upvotes: 0
Views: 1290
Reputation: 3348
Yes it is. You have to make a form where the user selects the fields they want to export, I'm thinking in a checkbox list where you list all the posible database fields the can get, and then create the query according the user selection. Ej:
<form action="" method="post">
<label><input name="fields[]" type="checkbox" value="name"> Username</label>
<label><input name="fields[]" type="checkbox" value="birthdate"> Birthdate</label>
</form>
And then on the server side create the database query.
$sql = "SELECT `". implode("`, `", $_POST["fields"]) ."` FROM db_table";
Hope this help.
Upvotes: 2