troubleshooting Question

Creating a CSV file without every column heading

Avatar of Bruce Gust
Bruce GustFlag for United States of America asked on
PHP
2 Comments2 Solutions315 ViewsLast Modified:
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?
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 2 Answers and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros