Avatar of Bruce Gust
Bruce Gust
Flag for United States of America asked on

Creating a CSV file without every column heading

This is the code that I'm using to create a csv file based on a query:

$fp = fopen('spreadsheets/voter_not_validated.csv', 'w');
// we capture the structure in order to catch the field names
$headings=array();
$bruce_query = "DESCRIBE registration";
$bruce_recordset = mysqli_query($cxn, $bruce_query)
or die ("Couldn't excute query.");
while($bruce_row=mysqli_fetch_assoc($bruce_recordset)) {
    $headings[ ]=$bruce_row['Field'];
}
fputcsv($fp, $headings, ',', '"'); // this save the headings whether you have data  or not.

$bruce_query = "select * from registration WHERE registration_type <> 'fan' AND (voter_validation='' OR voter_validation=' ') AND
songwriting_contest BETWEEN '2011-03-01' AND '2011-12-31' order by first_name";
$bruce_recordset = mysqli_query($cxn, $bruce_query)
or die ("Couldn't excute query.");
while($bruce_row=mysqli_fetch_assoc($bruce_recordset)) {
    fputcsv($fp, $bruce_row, ',', '"');
}
fclose($fp);
echo "voter_not_validated.csv is created<BR>";

The great news is that it works wonderfully, however...

I want to create a csv file that only includes those columns that are relevant to the query. How do I initiate my csv file in a way where I'm not having to include all the columns in the original database? Right now, the "describe" dynamic, while it's working, is overkill and I'm having to doctor the resulting file a little bit before I can use it the way that I need to.

How do you create the csv file so it only has those columns that are referenced in the query as opposed to every column in the table sitting in the database?
PHP

Avatar of undefined
Last Comment
chrisbloom7

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
chrisbloom7

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy