homepage Welcome to WebmasterWorld Guest from 23.22.217.122
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Create CSV File from DB
woldie




msg:1313980
 10:40 am on Feb 11, 2005 (gmt 0)

Hello People,

I've been exhibiting at a show just recently, and I have list of contacts I need to collate and place them into a CSV file.

What I have is all the contacts from a DB, and its just a matter of doing one SQL query to get the name, email address etc and create a CSV file.

Can this be done?

Thanks

W.

 

woldie




msg:1313981
 11:45 am on Feb 11, 2005 (gmt 0)

Hi,

I've had a go...if anyone has a better solution, then feel free to post one.

Not quite sure if this will append to the end of the file, if you were to add more records.

Code:

<?
// 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 );

?>

Thanks.

jatar_k




msg:1313982
 6:11 pm on Feb 11, 2005 (gmt 0)

>> Not quite sure if this will append to the end of the file

for appending you would need to use a different setting in your fopen [ww.php.net]

'w'
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'a'
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

there are other options available on the manual page as well.

Your code looks fine though.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved