<?php
$user_admin=$_COOKIE["user_admin"];
$jahrgang=$_COOKIE["jahrgang"];

include("kurs/datenbankanbindung.php");     // f&uuml;gt die Datenbankanbindung ein: Sys:\php\includes\kurs\datenbankanbindung.php


$Use_Title = 1;
$now_date = date('Ydm_Hi');

$ProsID = $_GET['id'];

$db = dbconnect();
    $sql = "SELECT nachname Nachname,vorname Vorname, stg Studienzweig, ag AG, jahrgang Jahr, thema Thema, Korrektor, '' Note
             FROM skik_ergebnis,stud
            WHERE skik_ergebnis.uid = stud.uid
              AND skik_ergebnis.id = $ProsID
              AND stud.durchgefallen != 'Y'
            ORDER BY stud.nachname, stud.vorname";
#echo $sql;
$result = @$db->query($sql)
    or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());

$sel_fach = $db->query("SELECT FPRNr, bezeichnung FROM skik_kurs WHERE id='$ProsID'");
$fach = $sel_fach->fetch_array();

$title = "Sprachkurse / Interkulturelle Kompetenzen Kurs Nr. $fach[FPRNr], Jahrgang $jahrgang: $fach[bezeichnung]";

//header info for browser
header('Content-Encoding: UTF-8');
header("Content-type: text/csv; charset=UTF-8");
#header("Content-Type: text/comma-separated-values;charset=UTF-8");
echo "\xEF\xBB\xBF";
header("Content-Disposition: attachment; filename=themen_jahrgang_$jahrgang-$now_date.csv"); //header("Content-Disposition: attachment; filename=database_dump.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");


if ($Use_Title == 1){
echo("$title\n\n");
}


//define separator (defines columns in excel & tabs in word)
$sep = ";"; //tabbed character

//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysqli_num_fields($result); $i++) {
echo mysqli_fetch_field_direct($result,$i)->name . ";";
}
print("\n");
//end of printing column names

//start while loop to get data
/*
note: the following while-loop was taken from phpMyAdmin 2.1.0.
--from the file "lib.inc.php".
*/
    while($row = $result->fetch_array())
    {
        //set_time_limit(60); // HaRa
        $schema_insert = "";
        for($j=0; $j<mysqli_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "\"$row[$j]\"".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        //following fix suggested by Josue (thanks, Josue!)
        //this corrects output in excel when table fields contain \n or \r
        //these two characters are now replaced with a space
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
?>