Creating excel from database and sending as email attachment
<p>This is my code to fetch data from database table </p>



<pre><code>$sql = "select * from tbl_input_values where 1";
$result = mysql_query($sql);
$resultRows = mysql_num_rows($result);
</code></pre>

<p>The below is the header that I used to download file as excel format:</p>



<pre><code>header("Content-Type: application/vnd.ms-excel");   
header("Content-Disposition: attachment; filename=test.xls");

header("Pragma: no-cache");
header("Expires: 0");
</code></pre>

<p>And my code to fetch the record is as follows:</p>



<pre><code>if($resultRows&gt;0){
    $sep = "\t"; //tabbed character
    for ($i = 0; $i &lt; mysql_num_fields($result); $i++) {
        echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
        $schema_insert = "";
        for($j=0; $j&lt;mysql_num_fields($result);$j++){
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t"; 
        print(trim(str_replace(',', " ", $schema_insert)));
        print "\n";
    }
}
</code></pre>

<p><strong>The code is working fine.</strong></p>

<p>So now I have to email this attachment instead of downloading it. Means when user want to create excel file the excel will be emailed to given email id.</p>

<p>So what would be the better way to use email functionality?</p>
