i have a php code that outputs a query from mysql. after output i would like to export it to a csv (excel) file. what i have now are two php files. one for the query and the other for the csv export. i tried to put the csv output file inside the first as a function BUT it doesn't work. here is the file:
Code: Select all
<?
// DB CONNECTION
........
// The database query
$result = query his here
//now the function
function getcsv()
{
$export = mysql_query ( $resule ) 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=data.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
}
$totalrows = mysql_num_rows($result);
if ($row = mysql_fetch_array($result)) {
do {
//following is the output of the search
............
} while($row = mysql_fetch_array($result));
} else {print "<font color=#FF0000><b>Sorry, no records were found!</font></b>";}
echo "<table bgcolor=#FFFEEF border=0 cellpadding=1 cellspacing=0 style=border-collapse: collapse bordercolor=#111111 width=100%>
<td align=left width=70% valign=top><font face=Verdana size=2 color=#FF0000><br><b>$totalrows</b></font><font face=Verdana size=2 color=#800000> record(s) found !</font></b></td>
//call the function
<tr><td>
<script>
function getcsv(){
}
</script>
<input type='button' onclick='getcsv()' value='Export as Excel File!'></td></tr>
</table>";
?>