Home > Article > Backend Development > How to import and export employee attendance data through PHP?
How to import and export employee attendance data through PHP?
In the daily management of an enterprise, the import and export of employee attendance data is a very important task. The import and export function of employee attendance data can be easily realized through the PHP programming language. This article will introduce how to use PHP to achieve this function and provide specific code examples.
1. Import employee attendance data
<form action="import.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" accept=".csv"> <input type="submit" value="导入"> </form>
<?php // 导入数据 if ($_SERVER["REQUEST_METHOD"] == "POST") { // 获取上传的文件 $file = $_FILES['file']['tmp_name']; // 连接数据库 $conn = new mysqli('localhost', 'username', 'password', 'database_name'); // 读取CSV文件 if (($handle = fopen($file, "r")) !== false) { while (($data = fgetcsv($handle, 1000, ",")) !== false) { // 将数据插入数据库 $sql = "INSERT INTO attendance (employee_id, date, start_time, end_time) VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]')"; $conn->query($sql); } fclose($handle); } // 关闭数据库连接 $conn->close(); // 导入成功提示 echo "导入成功"; } ?>
In the above code, first obtain the uploaded CSV file, then connect to the database and insert the data into the attendance data table row by row, and finally close the database connection and output a prompt that the import is successful. .
2. Export employee attendance data
<a href="export.php">导出</a>
<?php // 导出数据 // 连接数据库 $conn = new mysqli('localhost', 'username', 'password', 'database_name'); // 查询员工考勤数据 $sql = "SELECT * FROM attendance"; $result = $conn->query($sql); // 创建CSV文件 $file = fopen("attendance.csv", "w"); // 写入表头 fputcsv($file, array("员工ID", "日期", "上班时间", "下班时间")); // 写入数据 while ($data = $result->fetch_assoc()) { fputcsv($file, array($data['employee_id'], $data['date'], $data['start_time'], $data['end_time'])); } // 关闭文件 fclose($file); // 关闭数据库连接 $conn->close(); // 下载CSV文件 header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=attendance.csv"); readfile("attendance.csv"); ?>
In the above code, first connect to the database and query employee attendance data. Then create a CSV file and write the query results into the CSV file line by line. Finally, set the HTTP response headers to cause the browser to download the resulting CSV file.
Now, through the above code example, we can implement the import and export function of employee attendance data. Just add the code to the corresponding file and add the corresponding form or button to the HTML page. I hope this article can be helpful in implementing this function!
The above is the detailed content of How to import and export employee attendance data through PHP?. For more information, please follow other related articles on the PHP Chinese website!