0

I've got some php code which export mysql database to a .xls file. I can download immediately when I run the code. However, can I use php to send this file to an admin email account every time when below code generates a new .xls file?

Thanks.

<?php

    require_once('connect.php');

    $group = 1;//$_GET['group'];

    $export = mysql_query ("SELECT * FROM relationship WHERE group_id = $group");

    $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=your_desired_name.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    print "$header\n$data";

    mysql_close($my_connection);

    ?>
michael
  • 37
  • 1
  • 5
  • If you're creating a csv file (whether using tab or comma or any other character as the separator), use PHP's built-in [fputcsv()](http://www.php.net/manual/en/function.fputcsv.php) function... not only is it simpler, it handles all those little issues that your code doesn't, such as quoting strings, escaping quotes, allowing new lines in fields, etc – Mark Baker Oct 30 '13 at 09:52
  • If you want to send as an email attachment, then you want to save to file (or output buffer) rather than display to screen, so dump the headers and write to file, then attach that file to your email – Mark Baker Oct 30 '13 at 09:54
  • 2
    [Please, stop using mysql_* functions](http://stackoverflow.com/q/12859942/1238019) in new code, they are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Instead of, have a look on [prepared statements](http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html), and use [Mysqli](http://php.net/manual/en/book.mysqli.php) or [PDO](http://php.net/manual/en/book.pdo.php). – zessx Oct 30 '13 at 09:57

0 Answers0