You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP新手求助:删除CSV员工记录后如何覆盖原文件

Hey there! No worries at all—we all start somewhere with PHP, and this is such a practical project to learn file handling and form interactions. Let's build this feature step by step.

整体 Approach

We'll need to handle three main things:

  • Read and parse the employee_data.csv file into a usable array
  • Process the delete request when a user clicks the button (remove the selected employee from the array)
  • Write the updated array back to the CSV file, then render the updated table
Complete Working Code

Save this as employee_manager.php (or whatever name you prefer) — it handles both the backend logic and frontend display in one file:

<?php
// Define the CSV file path
$csvFile = 'employee_data.csv';

// Handle delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_index'])) {
    $deleteIndex = (int)$_POST['delete_index'];
    
    // Read all lines from CSV
    $employees = [];
    if (($handle = fopen($csvFile, 'r')) !== false) {
        while (($data = fgetcsv($handle)) !== false) {
            $employees[] = $data;
        }
        fclose($handle);
    }
    
    // Remove the selected employee (skip header row if your CSV has one)
    if (isset($employees[$deleteIndex])) {
        array_splice($employees, $deleteIndex, 1);
    }
    
    // Write updated data back to CSV
    if (($handle = fopen($csvFile, 'w')) !== false) {
        foreach ($employees as $row) {
            fputcsv($handle, $row);
        }
        fclose($handle);
    }
}

// Fetch updated employee data to display
$employees = [];
if (($handle = fopen($csvFile, 'r')) !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        $employees[] = $data;
    }
    fclose($handle);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Employee Manager</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 20px auto; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .delete-btn { background-color: #ff4444; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <h2 style="text-align: center;">Employee Records</h2>
    <?php if (!empty($employees)): ?>
        <table>
            <!-- Render header row (assuming first row is headers) -->
            <tr>
                <?php foreach ($employees[0] as $header): ?>
                    <th><?php echo htmlspecialchars($header); ?></th>
                <?php endforeach; ?>
                <th>Action</th>
            </tr>
            <!-- Render employee rows -->
            <?php foreach ($employees as $index => $employee): ?>
                <?php if ($index === 0) continue; // Skip header row for data rows ?>
                <tr>
                    <?php foreach ($employee as $field): ?>
                        <td><?php echo htmlspecialchars($field); ?></td>
                    <?php endforeach; ?>
                    <td>
                        <form method="POST" style="margin:0;">
                            <input type="hidden" name="delete_index" value="<?php echo $index; ?>">
                            <button type="submit" class="delete-btn" onclick="return confirm('Are you sure you want to delete this employee?');">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p style="text-align: center;">No employee records found.</p>
    <?php endif; ?>
</body>
</html>
Key Details to Note

Let's break down the important parts so you understand what's going on:

  1. CSV Handling:
    • We use fgetcsv() to read the file line by line, which automatically parses each CSV row into an array.
    • fputcsv() writes the updated array back to the file, ensuring proper CSV formatting (even if fields have commas or quotes).
  2. Delete Logic:
    • When the delete button is clicked, we send a POST request with the index of the row to delete.
    • array_splice() removes the specific row from the employee array. We skip the header row (index 0) when rendering delete buttons, so the first employee is index 1.
  3. Security & Best Practices:
    • We use htmlspecialchars() when rendering employee data to prevent XSS attacks (super important even for small projects!).
    • The confirm() dialog gives users a chance to cancel before deleting.
    • We check $_SERVER['REQUEST_METHOD'] to make sure we only process delete requests when a POST is sent.
Setup Notes
  • Make sure your employee_data.csv has a header row (like ID,Name,Email,Department) followed by employee data.
  • Ensure PHP has write permissions for the directory where employee_data.csv is stored (otherwise it can't update the file).

If you run into any issues—like permission errors or unexpected CSV parsing—just let me know, and we can troubleshoot together!

内容的提问来源于stack exchange,提问作者Celt67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:37:55