<?php include("session_controller.php"); ?>
<?php
//echo $_SESSION['query'] ;
mysqli_select_db($conn, $database_conn);
//http://www.the-art-of-web.com/php/dataexport/
// Original PHP code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // filename for download
  $filename = "account_data_" . date('Ymdgis') . ".xls";
  //$filename = "account_data_" . date('Ymdgis') . ".csv";


  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");
 //header("Content-Type: text/plain");

  $flag = false;
  $result = NULL;
  if(isset($_SESSION['query']) && ($_SESSION['query'] != "")){
  $result = mysqli_query($conn, $_SESSION['query'])  or die('Query failed!');
 
  
  do{
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
  } while($row = mysqli_fetch_assoc($result)) ;
  
  }
  
   unset($_SESSION['query']);// unset the session
 
  exit;
?>