<?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";

$fp = fopen($filename, 'w');

 // 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!');
 
 // "SELECT m.s_no, m.account_no, m.credit, m.debit, m.balance, m.tranx_details, m.tranx_id, m.tranx_date, s.surname, s.firstname, s.middlename, s.phone FROM tranx m JOIN accounts s ON (m.account_no = s.account_no) $missing ORDER BY m.s_no DESC"

  do {
    fputcsv($fp, [$row['m.no'], $row['m.account_no'], $row['m.credit'], $row['m.debit'], $row['m.balance'], $row['m.tranx_details'], $row['m.tranx_id'], $row['m.tranx_date'], $row['s.surname'], $row['s.firstname'], $row['s.middlename'], $row['s.phone']] );
  }while($row = mysqli_fetch_assoc($result));
  
  fclose($fp);
  }
  else{
      
  }
  
   unset($_SESSION['query']);// unset the session
 
  exit;
?>