|
1 | 1 | <?php
|
| 2 | +// Function to sanitize input data |
| 3 | +function sanitize_input($data) { |
| 4 | + return htmlspecialchars(trim($data)); |
| 5 | +} |
| 6 | + |
2 | 7 | try {
|
3 | 8 | // Connect to SQLite database
|
4 | 9 | $db = new PDO('sqlite:students.db');
|
| 10 | + |
| 11 | + // Set error mode to throw exceptions |
5 | 12 | $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
6 | 13 |
|
7 |
| - // Insert data into Attendance table |
| 14 | + // Sanitize and validate inputs |
| 15 | + $roll_no = sanitize_input($_POST['roll_no']); |
| 16 | + $student_name = sanitize_input($_POST['student_name']); |
| 17 | + |
| 18 | + // Check if any field is empty |
| 19 | + if (empty($roll_no) || empty($student_name)) { |
| 20 | + throw new Exception("All fields are required."); |
| 21 | + } |
| 22 | + |
| 23 | + // Prepare SQL statement to insert data |
8 | 24 | $stmt = $db->prepare("INSERT INTO Attendance (roll_no, student_name, date) VALUES (:roll_no, :student_name, :date)");
|
9 |
| - $stmt->bindParam(':roll_no', $_POST['roll_no']); |
10 |
| - $stmt->bindParam(':student_name', $_POST['student_name']); |
| 25 | + $stmt->bindParam(':roll_no', $roll_no); |
| 26 | + $stmt->bindParam(':student_name', $student_name); |
11 | 27 | $stmt->bindParam(':date', date('Y-m-d'));
|
| 28 | + |
| 29 | + // Execute SQL statement |
12 | 30 | $stmt->execute();
|
13 | 31 |
|
| 32 | + // Success message |
14 | 33 | echo "Attendance recorded successfully.";
|
15 |
| -} catch (PDOException $e) { |
16 |
| - echo "Error: " . $e->getMessage(); |
| 34 | +} catch (Exception $e) { |
| 35 | + // Log error to server logs |
| 36 | + error_log("Error: " . $e->getMessage()); |
| 37 | + |
| 38 | + // Error message for users |
| 39 | + echo "An error occurred. Please try again later."; |
17 | 40 | }
|
18 | 41 | ?>
|
0 commit comments