Table of Contents
员工列表
Home Backend Development PHP Tutorial How to develop an online employee attendance application with PHP and Vue

How to develop an online employee attendance application with PHP and Vue

Sep 24, 2023 pm 05:13 PM
php vue Online employee attendance

How to develop an online employee attendance application with PHP and Vue

How to develop an online employee attendance application with PHP and Vue

Abstract: With the rapid development of technology, more and more companies choose to transfer employee attendance systems to online platforms. This article will introduce how to use PHP and Vue, two popular development technologies, to develop an online employee attendance application. We will provide specific code examples to help readers better understand and apply.

  1. Environment setup

Before you begin, please make sure your development environment is set up correctly. You need to install a development environment for PHP and Vue, such as XAMPP (for Windows users) or MAMP (for Mac users). At the same time, you also need a database server to store employee attendance data, such as MySQL.

  1. Create database

Use a MySQL administrator tool (such as phpMyAdmin) to create a new database to store employee attendance data. Create a database named "attendance", then create a table named "employees" to store employee information, and a table named "attendances" to store employee attendance records. The following is an example of SQL code to create these two tables:

Create employees table:

CREATE TABLE employees (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    department VARCHAR(100) NOT NULL
);
Copy after login

Create attendances table:

CREATE TABLE attendances (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    employee_id INT(11) NOT NULL,
    check_in DATETIME NOT NULL,
    check_out DATETIME,
    FOREIGN KEY (employee_id) REFERENCES employees(id)
);
Copy after login
  1. Backend Development - PHP

First, we need to create a PHP file to handle the backend logic. We can name this file "api.php". In this file, we will write the code for data interaction with the front-end Vue application through the API. Here is a simple example:

<?php

header('Content-Type: application/json');

// 连接到数据库
$dsn = 'mysql:host=localhost;dbname=attendance';
$username = 'root';
$password = '';

try {
    $db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo '数据库连接失败: ' . $e->getMessage();
    exit();
}

// 获取所有员工信息
function getEmployees() {
    global $db;
    
    $stmt = $db->prepare('SELECT * FROM employees');
    $stmt->execute();
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 添加新的考勤记录
function addAttendance($employeeId, $checkIn) {
    global $db;
    
    $stmt = $db->prepare('INSERT INTO attendances(employee_id, check_in) VALUES(?, ?)');
    $stmt->execute([$employeeId, $checkIn]);
    
    return $db->lastInsertId();
}

// 更新考勤记录
function updateAttendance($attendanceId, $checkOut) {
    global $db;
    
    $stmt = $db->prepare('UPDATE attendances SET check_out = ? WHERE id = ?');
    $stmt->execute([$checkOut, $attendanceId]);
    
    return $stmt->rowCount();
}

// 获取指定员工的考勤记录
function getAttendances($employeeId) {
    global $db;
    
    $stmt = $db->prepare('SELECT * FROM attendances WHERE employee_id = ?');
    $stmt->execute([$employeeId]);
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 根据传入的API请求参数调用相应的函数
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    if ($action === 'getEmployees') {
        echo json_encode(getEmployees());
    } else if ($action === 'addAttendance') {
        $employeeId = $_POST['employeeId'];
        $checkIn = $_POST['checkIn'];
        
        echo json_encode(['id' => addAttendance($employeeId, $checkIn)]);
    } else if ($action === 'updateAttendance') {
        $attendanceId = $_POST['attendanceId'];
        $checkOut = $_POST['checkOut'];
        
        echo json_encode(['rowsAffected' => updateAttendance($attendanceId, $checkOut)]);
    } else if ($action === 'getAttendances') {
        $employeeId = $_GET['employeeId'];
        
        echo json_encode(getAttendances($employeeId));
    }
}
Copy after login

In this PHP file, we first connect to the database and define some functions to handle various API requests. Specific logic includes obtaining employee information, adding/updating attendance records, and obtaining attendance records of specified employees.

Here, we only provide some basic example functions, which you can extend and modify according to your actual needs.

  1. Front-End Development - Vue

Next, we will use Vue to develop front-end applications. We need to create a Vue instance to render and manage the application's interface and logic. The following is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>员工考勤应用程序</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <h1 id="员工列表">员工列表</h1>
    <ul>
      <li v-for="employee in employees" :key="employee.id">
        {{ employee.name }} - {{ employee.department }}
        <button @click="addAttendance(employee.id)">签到</button>
      </li>
    </ul>
  </div>

  <script>
    new Vue({
        el: "#app",
        data: {
            employees: []
        },
        mounted() {
            this.getEmployees();
        },
        methods: {
            getEmployees() {
                fetch('api.php?action=getEmployees')
                    .then(response => response.json())
                    .then(data => {
                        this.employees = data;
                    });
            },
            addAttendance(employeeId) {
                fetch('api.php?action=addAttendance', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        employeeId: employeeId,
                        checkIn: new Date().toISOString()
                    })
                })
                .then(response => response.json())
                .then(data => {
                    alert(`签到成功,考勤ID: ${data.id}`);
                });
            }
        }
    });
  </script>
</body>
</html>
Copy after login

In this example, we first introduce the Vue JavaScript file. Then, we created a Vue instance, defined a list of employees and two methods to obtain employee information and add attendance records. When the page is loaded, the Vue instance will automatically call the mounted method to obtain employee information and bind them to the employees property. In the list, we use the v-for directive to loop through each employee and add a check-in button for each employee. When the user clicks the sign-in button, the addAttendance method will be triggered to initiate a request to add an attendance record to the backend, and a successful sign-in prompt will be displayed after success.

It should be noted that the API request in this example uses the fetch function to initiate an asynchronous request. You can also use other similar libraries, such as axios.

  1. Conclusion

By using PHP and Vue to develop an online employee attendance application, we can implement a simple and practical employee attendance system. In this article, we provide specific code examples to help readers understand the data storage and interaction process. Of course, this is just a basic framework, and you can extend and modify it according to your needs and actual conditions. I hope this article will help you understand how to use PHP and Vue to develop an online employee attendance application.

The above is the detailed content of How to develop an online employee attendance application with PHP and Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles