Forum Moderators: coopster
I am currently able to export successfully the contents of a query into a Comma Delimited text file using the code below. WHat i need is for the the code to also export the Column Names so that they appear in the first row of the file. I was researching but was unable to come up with a concrete solution. Can anybody point me in the right direction? Something to do with mysql_field_name but im not quite sure how to integrate that with the code below...
<?
// connect to database
$result=mysql_query("select id
from tablename
where shid=3");
list($DBshid)=mysql_fetch_row($result);
/***********************************
Write Date to CSV file
***********************************/
$_file = 'show.csv';
$_fp = @fopen( $_file, 'w' );
$result=mysql_query("select name,compname,job_title,email_add,phone,url
from tablename
where id=3");
while (list($DBname,$DBcompname,$DBjob_title,$DBemail_add,$DBphone,$DBurl)=mysql_fetch_row($result))
{
$_csv_data=$DBname.','.$DBcompname.','.$DBjob_title.','.$DBemail_add.','.$DBphone.','.$DBurl . "\n";
@fwrite( $_fp, $_csv_data );
}
@fclose( $_fp );
?>
$_csv_data = "Name, Company name, Job title, Email, Phone, Url\n";
$result=mysql_query("SELECT name,compname,job_title,email_add,phone,url
FROM tablename
WHERE id=3");
while (list($DBname,$DBcompname,$DBjob_title,$DBemail_add,$DBphone,$DBurl)=mysql_fetch_row($result))
{
$_csv_data .= "$DBname,$DBcompname,$DBjob_title,$DBemail_add,$DBphone,$DBurl\n";
}
$_file = 'show.csv';
$_fp = @fopen( $_file, 'w' );
@fwrite( $_fp, $_csv_data );
@fclose( $_fp );
?>
And voile, you've got yourself a csv with headers :)
Regards
Michal
or before while use:
$result=mysql_query("SELECT name,compname,job_title,email_add,phone,url
FROM tablename
WHERE id=3");
$_csv_data = mysql_field_name($result, 0).','.mysql_field_name($result, 1).','.mysql_field_name($result, 2)...
while (list($DBname,$DBcompname,$DBjob_title,$DBemail_add,$DBphone,$DBurl)=mysql_fetch_row($result))
{
WORKED LIKE A CHAMP! i ended up using mcibor response just because i wasnt sure how to incorperate that into the exisiting code
One more question though...
How would i go about naming the file using the value from $DBfirstname...
I tried something like this but its not working
$_file = '$DBname.csv';