We help IT Professionals succeed at work.
Get Started

Creating a CSV file without every column heading

Bruce Gust
Bruce Gust asked
on
313 Views
Last Modified: 2012-05-11
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?
Comment
Watch Question
Most Valuable Expert 2011
Author of the Year 2014
Commented:
This problem has been solved!
Unlock 2 Answers and 2 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE