0

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";
}
7
  • 2
    yes, now with out more details that's all you get. Commented Feb 8, 2012 at 3:15
  • Yes it is possible. In that case you have to generate the particular SQL statements programatically. Commented Feb 8, 2012 at 3:16
  • how do i generate the SQL Statement programatically? Commented Feb 8, 2012 at 3:25
  • how about showing some code so we at least have a clue, do you rally think you have provided enough information for any one to be able to help you? Commented Feb 8, 2012 at 3:32
  • I have added in the necessary code. Any ideas? I am getting unknown column name errors.. Commented Feb 9, 2012 at 0:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When i tried using this, I got the - unknown column author in fieldlist - error. Also, i used this type of query earlier: $query = sprintf("select x from y");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.