Pages

Thursday, March 25, 2010

Export DB result in CSV file format

ini_set("display_errors",0);

include_once("inc.db_connect.php");
connect();

function exportMysqlToCsv($export = false,$filename = 'export.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = " select c.fname, c.lname, c.email, co.product_name, co.status
from customers as c
JOIN customer_orders as co on c.id = co.customer_id  
where co.status = 'ABANDONED'
group by c.id";
 
    // Gets the data from the database
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);


    $schema_insert = '';

    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for

    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;

  
    print("");
    print("
");
    print("
");
    // Format the data
    while ($row = mysql_fetch_array($result))
    {
     if($export)
     {
       $schema_insert = '';
       for ($j = 0; $j < $fields_cnt; $j++)
       {
           if ($row[$j] == '0' || $row[$j] != '')
           {

               if ($csv_enclosed == '')
               {
                   $schema_insert .= $row[$j];
               } else
               {
                   $schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
               }
           } else
           {
               $schema_insert .= '';
           }

           if ($j < $fields_cnt - 1)
           {
               $schema_insert .= $csv_separator;
           }
       } // end for

       $out .= $schema_insert;
       $out .= $csv_terminated;
     }
     else{
     extract($row);
     print('
');
     }
    
    } // end while

    echo "
NameEmailProductStatus
' . $fname . ' ' . $lname . '' . $email . '' . $product_name . '' . $status . '
";
    if($export){
   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
   header("Content-Length: " . strlen($out));
   // Output to browser with appropriate mime type, you choose ;)
   header("Content-type: text/x-csv");
   //header("Content-type: text/csv");
   //header("Content-type: application/csv");
   header("Content-Disposition: attachment; filename=$filename");
   echo $out;
   exit;
    }
}

use it in a following way.



if($_GET['export'']){
exportMysqlToCsv(true);
}
else{
exportMysqlToCsv();
}

?>




?>

No comments:

Post a Comment