search
HomeBackend DevelopmentPHP TutorialHow to use PHP and Vue to build the check-in location setting function for employee attendance

How to use PHP and Vue to build the check-in location setting function for employee attendance

How to use PHP and Vue to build the check-in location setting function for employee attendance

In recent years, with the development of technology and the progress of society, more and more enterprises Public institutions began to adopt electronic methods for employee attendance management. One of the important links is the setting of employee check-in locations. In this article, we will introduce how to use PHP and Vue to build a check-in location setting function for employee attendance, and provide specific code examples.

1. Preparation

Before we start, we need to prepare the required development environment. We need a server, which can be built using Apache or Nginx. At the same time, we also need to install PHP and MySQL as the back-end development language and database. In addition, we also need to install Node.js and Vue.js as front-end development tools.

2. Create a database

First, we need to create a database to store employee related information and check-in locations. You can use tools such as Navicat or phpMyAdmin to create a database named "attendance" and create two tables in it, "employees" and "locations".

The structure of the employees table is as follows:

CREATE TABLE employees (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  job_title VARCHAR(50) NOT NULL,
  department VARCHAR(50) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The structure of the locations table is as follows:

CREATE TABLE locations (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  address VARCHAR(100) NOT NULL,
  latitude DECIMAL(10, 6) NOT NULL,
  longitude DECIMAL(10, 6) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. Back-end development

  1. Create an api. php file that handles requests sent by the front end and interacts with the database.
<?php
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

// 处理GET请求,查询数据库中的员工和签到地点信息
if ($method === 'GET') {
  $action = $_GET['action'];
  
  // 查询员工信息
  if ($action === 'employees') {
    // 连接数据库
    $conn = new mysqli('localhost', 'root', '', 'attendance');
    mysqli_set_charset($conn, "utf8");
    
    // 查询数据库中的员工信息
    $result = $conn->query('SELECT * FROM employees');
    $employees = $result->fetch_all(MYSQLI_ASSOC);
    
    // 返回员工信息
    echo json_encode($employees);
    
    // 关闭数据库连接
    $conn->close();
  }
  
  // 查询签到地点信息
  else if ($action === 'locations') {
    // 连接数据库
    $conn = new mysqli('localhost', 'root', '', 'attendance');
    mysqli_set_charset($conn, "utf8");
    
    // 查询数据库中的签到地点信息
    $result = $conn->query('SELECT * FROM locations');
    $locations = $result->fetch_all(MYSQLI_ASSOC);
    
    // 返回签到地点信息
    echo json_encode($locations);
    
    // 关闭数据库连接
    $conn->close();
  }
}

// 处理POST请求,添加员工和签到地点信息到数据库
else if ($method === 'POST') {
  $data = json_decode(file_get_contents('php://input'), true);
  $action = $data['action'];

  // 添加员工信息
  if ($action === 'addEmployee') {
    // 连接数据库
    $conn = new mysqli('localhost', 'root', '', 'attendance');
    mysqli_set_charset($conn, "utf8");
    
    // 添加员工信息到数据库
    $name = $data['name'];
    $job_title = $data['job_title'];
    $department = $data['department'];
    $conn->query("INSERT INTO employees (name, job_title, department) VALUES ('$name', '$job_title', '$department')");

    // 返回成功信息
    echo json_encode(['status' => 'success']);

    // 关闭数据库连接
    $conn->close();
  }
  
  // 添加签到地点信息
  else if ($action === 'addLocation') {
    // 连接数据库
    $conn = new mysqli('localhost', 'root', '', 'attendance');
    mysqli_set_charset($conn, "utf8");

    // 添加签到地点信息到数据库
    $name = $data['name'];
    $address = $data['address'];
    $latitude = $data['latitude'];
    $longitude = $data['longitude'];
    $conn->query("INSERT INTO locations (name, address, latitude, longitude) VALUES ('$name', '$address', '$latitude', '$longitude')");

    // 返回成功信息
    echo json_encode(['status' => 'success']);

    // 关闭数据库连接
    $conn->close();
  }
}
?>
  1. Start the server and place the api.php file in the root directory of the server.

4. Front-end development

  1. Create an index.html file to display information about employees and check-in locations, and provide the function of adding employees and check-in locations.
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>员工考勤签到地点设置</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <h2 id="员工信息">员工信息</h2>
    <table>
      <tr>
        <th>姓名</th>
        <th>职位</th>
        <th>部门</th>
      </tr>
      <tr v-for="employee in employees">
        <td>{{ employee.name }}</td>
        <td>{{ employee.job_title }}</td>
        <td>{{ employee.department }}</td>
      </tr>
    </table>

    <form @submit.prevent="addEmployee">
      <input type="text" v-model="newEmployee.name" placeholder="姓名" required>
      <input type="text" v-model="newEmployee.job_title" placeholder="职位" required>
      <input type="text" v-model="newEmployee.department" placeholder="部门" required>
      <button type="submit">添加员工</button>
    </form>

    <h2 id="签到地点">签到地点</h2>
    <table>
      <tr>
        <th>名称</th>
        <th>地址</th>
        <th>经度</th>
        <th>纬度</th>
      </tr>
      <tr v-for="location in locations">
        <td>{{ location.name }}</td>
        <td>{{ location.address }}</td>
        <td>{{ location.latitude }}</td>
        <td>{{ location.longitude }}</td>
      </tr>
    </table>

    <form @submit.prevent="addLocation">
      <input type="text" v-model="newLocation.name" placeholder="名称" required>
      <input type="text" v-model="newLocation.address" placeholder="地址" required>
      <input type="text" v-model="newLocation.latitude" placeholder="经度" required>
      <input type="text" v-model="newLocation.longitude" placeholder="纬度" required>
      <button type="submit">添加签到地点</button>
    </form>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        employees: [],
        newEmployee: {
          name: '',
          job_title: '',
          department: ''
        },
        locations: [],
        newLocation: {
          name: '',
          address: '',
          latitude: '',
          longitude: ''
        }
      },
      methods: {
        addEmployee() {
          fetch('api.php', {
            method: 'POST',
            body: JSON.stringify({
              action: 'addEmployee',
              name: this.newEmployee.name,
              job_title: this.newEmployee.job_title,
              department: this.newEmployee.department
            })
          })
          .then(() => {
            this.employees.push(this.newEmployee);
            this.newEmployee = { name: '', job_title: '', department: '' };
          });
        },
        addLocation() {
          fetch('api.php', {
            method: 'POST',
            body: JSON.stringify({
              action: 'addLocation',
              name: this.newLocation.name,
              address: this.newLocation.address,
              latitude: this.newLocation.latitude,
              longitude: this.newLocation.longitude
            })
          })
          .then(() => {
            this.locations.push(this.newLocation);
            this.newLocation = { name: '', address: '', latitude: '', longitude: '' };
          });
        }
      },
      mounted() {
        fetch('api.php?action=employees')
          .then(response => response.json())
          .then(employees => {
            this.employees = employees;
          });

        fetch('api.php?action=locations')
          .then(response => response.json())
          .then(locations => {
            this.locations = locations;
          });
      }
    });
  </script>
</body>
</html>
  1. Also place the index.html file in the root directory of the server.

5. Run the project

  1. Start Apache (or Nginx) and MySQL server.
  2. Access the index.html file in the browser, you can see the information of employees and check-in locations, and you can add new employees and check-in locations.

Through the above steps, we successfully used PHP and Vue to build the check-in location setting function for employee attendance, and provided specific code examples. We hope it will be helpful to you. Of course, in practical applications, further development and improvement are required based on specific needs.

The above is the detailed content of How to use PHP and Vue to build the check-in location setting function for employee attendance. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version