HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux host 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: w230 (1248)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/w230/html/behavior/export_behavior_csv.php
<?php
include 'db.php';

if (!isset($_GET['student_id']) || empty($_GET['student_id'])) {
    die("กรุณาระบุ student_id ใน URL");
}

$student_id = mysqli_real_escape_string($conn, $_GET['student_id']);

// ดึงชื่อนักเรียน
$student_query = mysqli_query($conn, "SELECT fullname FROM students WHERE id = '$student_id'");
$student = mysqli_fetch_assoc($student_query);
$student_name = $student['fullname'] ?? 'ไม่ทราบชื่อ';

// ตั้งค่า header สำหรับดาวน์โหลดเป็น CSV
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=behavior_' . $student_name . '.csv');

// เปิด output stream
$output = fopen('php://output', 'w');
fputs($output, "\xEF\xBB\xBF"); // เข้ารหัส UTF-8 BOM สำหรับภาษาไทย

// เขียนหัวตาราง
fputcsv($output, ['วันที่', 'ชื่อนักเรียน', 'พฤติกรรม', 'คะแนนที่ตัด']);

// ดึงข้อมูลพฤติกรรม
$sql = "SELECT behavior.created_at, students.fullname, behavior.behavior_detail, behavior.points
        FROM behavior 
        JOIN students ON behavior.student_id = students.id 
        WHERE behavior.student_id = '$student_id'
        ORDER BY behavior.created_at DESC";
$result = mysqli_query($conn, $sql);

$total_deducted = 0;

// เขียนข้อมูลลงไฟล์
while ($row = mysqli_fetch_assoc($result)) {
    fputcsv($output, [
        $row['created_at'],
        $row['fullname'],
        $row['behavior_detail'],
        $row['points']
    ]);
    $total_deducted += $row['points'];
}

// คะแนนเริ่มต้น 100 หักคะแนนรวม - เปล่ี่ยนเป็น + เนื่องจากคะแนนติด-ด้านหน้า
$remaining = 100 + $total_deducted;

// เขียนบรรทัดสรุป
fputcsv($output, []);
fputcsv($output, ['รวมคะแนนที่ถูกตัด', '', '', $total_deducted]);
fputcsv($output, ['คะแนนคงเหลือ', '', '', $remaining]);

fclose($output);
exit();
?>