<?php
	require_once('source/dbConfig.php');
	

//get records from database
$query = $db->query("SELECT * FROM tbl_student_results ORDER BY id DESC");

if($query->num_rows > 0){
    $delimiter = ",";
    $filename = "Results_" . date('Y-m-d') . ".csv";
    
    //create a file pointer
    $f = fopen('php://memory', 'w');
    
    //set column headers
    $fields = array('ID', 'Name', 'Registration_no', 'Test', 'Home_work', 'Project', 'Exam', 'Total', 'Grade');
    fputcsv($f, $fields, $delimiter);
    
    //output each row of the data, format line as csv and write to file pointer
    while($row = $query->fetch_assoc()){
        $status = ($row['status'] == '1')?'Active':'Inactive';
        $lineData = array($row['id'], $row['name'], $row['registration_no'], $row['test'], $row['home_work'], $row['project'], $row['exam'], $row['total'], $row['grade']);
        fputcsv($f, $lineData, $delimiter);
    }
    
    //move back to beginning of file
    fseek($f, 0);
    
    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    
    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;

?>