Create a PHP script that connects to a SQLite database and performs basic CRUD operations on a table storing employee records (employee ID, first name, last name, department, and salary). Include validation checks for the input data and display the results in an HTML table.
PLAINFORMAT
<?php

// Create the SQLite connection
$db = new PDO('sqlite:employees.db');

// Create the employees table if it doesn't exist
$db->exec("CREATE TABLE IF NOT EXISTS employees (
    id INTEGER PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    department TEXT NOT NULL,
    salary REAL NOT NULL)");

// Function to sanitize input data
function clean_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Handle form submissions
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize input data
    $first_name = clean_input($_POST["first_name"]);
    $last_name = clean_input($_POST["last_name"]);
    $department = clean_input($_POST["department"]);
    $salary = clean_input($_POST["salary"]);

    // Insert the record into the employees table
    $stmt = $db->prepare("INSERT INTO employees (first_name, last_name, department, salary) VALUES (?, ?, ?, ?)");
    $stmt->execute([$first_name, $last_name, $department, $salary]);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Records</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
    </style>
</head>
<body>

<h2>Add Employee Record</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    First Name: <input type="text" name="first_name" required><br>
    Last Name: <input type="text" name="last_name" required><br>
    Department: <input type="text" name="department" required><br>
    Salary: <input type="number" step="0.01" name="salary" required><br>
    <input type="submit" value="Submit">
</form>

<h2>Employee Records</h2>
<table>
    <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Department</th>
        <th>Salary</th>
    </tr>
    <?php
    // Fetch all records from the employees table and display them in an HTML table
    $result = $db->query("SELECT * FROM employees");
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['first_name'] . "</td>";
        echo "<td>" . $row['last_name'] . "</td>";
        echo "<td>" . $row['department'] . "</td>";
        echo "<td>" . $row['salary'] . "</td>";
        echo "</tr>";
    }
    ?>
</table>

</body>
</html>