Page 1 of 1

export to csv (SOLVED in a way!)

Posted: Tue Sep 09, 2008 1:14 pm
by sirTemplar
i have a script that queries my MySql database, after the search and output i would like to be able to export the result into a csv format. is this possible and how? thank you

Re: export to csv

Posted: Tue Sep 09, 2008 1:16 pm
by dude81
Yes, it is possible, for "export to csv" search this forum that could through you huge results.

Re: export to csv

Posted: Tue Sep 09, 2008 2:25 pm
by pickle
fputcsv() is a nice function if your system is up to date.

Re: export to csv

Posted: Wed Sep 10, 2008 3:51 am
by sirTemplar
thank you. searching the net, i found the following code. it does what i want just that it's exporting ALL FIELDS, and is TAB separated. i want to separate it with a comma (,) and export only some fields.

Code: Select all

 
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
 
$fields = mysql_num_fields ( $export );
 
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
 
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
 
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=database.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";