Pages

Wednesday 10 April 2013

How to show table records in Exale formate in php


<?php
ob_start();
ob_flush();
$conn = mysql_connect("localhost","root","")
    or die("Connecting to MySQL failed");

mysql_select_db('sugan_php')
    or die("Selecting MySQL database failed");


?>


<?php
 
$showtablequery = "SHOW TABLES FROM sugan_php";

$showtablequery_result    = mysql_query($showtablequery);
while($showtablerow = mysql_fetch_array($showtablequery_result))
{
    echo $showtablerow[0]."<br />";
}


exit;
?>

<?php
$file_name="mycsv";
$header="";
$data="";
//create query to select as data from your table
$select = "SELECT * FROM test1";

//run mysql query and then count number of fields
$export = mysql_query ( $select )
       or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );

//create csv header row, to contain table headers
//with database field names
for ( $i = 0; $i < $fields; $i++ ) {
    $header .= mysql_field_name( $export , $i ) . ",";
}

//this is where most of the work is done.
//Loop through the query results, and create
//a row for each
while( $row = mysql_fetch_row( $export ) ) {
    $line = '';
    //for each field in the row
    foreach( $row as $value ) {
        //if null, create blank field
        if ( ( !isset( $value ) ) || ( $value == "" ) ){
            $value = ",";
        }
        //else, assign field value to our data
        else {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . ",";
        }
        //add this field value to our row
        $line .= $value;
    }
    //trim whitespace from each row
    $data .= trim( $line ) . "\n";
}
//remove all carriage returns from the data
$data = str_replace( "\r" , "" , $data );
//$mydate=date("Y-m-d");


//create a file and send to browser for user to download

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$file_name.".csv");
print "$header\n$data";
exit;
?>

No comments:

Post a Comment