Home  >  Article  >  Backend Development  >  How to use PHP to implement the alarm clock function of WeChat applet?

How to use PHP to implement the alarm clock function of WeChat applet?

王林
王林Original
2023-10-27 16:58:52966browse

How to use PHP to implement the alarm clock function of WeChat applet?

How to use PHP to implement the alarm clock function of WeChat applet?

With the popularity of WeChat mini programs, more developers have begun to pay attention to how to implement various practical functions in WeChat mini programs. Among them, the alarm clock function is one of the very practical functions. This article will introduce how to use PHP to write a back-end interface and combine it with the front-end code of the WeChat applet to implement a simple alarm clock function.

  1. Create database table

First, we need to create a database table to store alarm clock related information. You can use the following SQL statement to create a table named "alarm":

CREATE TABLE `alarm` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `user_id` INT(11) NOT NULL,
  `time` INT(11) NOT NULL,
  `is_enabled` TINYINT(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. Writing the back-end interface

Next, we use PHP to write the back-end interface, Used to process requests sent from WeChat applet. Create a file named "alarm.php" and write the following code:

<?php

// 连接数据库
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'your_username';
$password = 'your_password';

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// 设置字符集
$pdo->exec('SET NAMES utf8');

// 处理添加闹钟请求
if ($_GET['action'] == 'add') {
    $user_id = $_GET['user_id'];
    $time = $_GET['time'];
    
    $stmt = $pdo->prepare('INSERT INTO alarm (user_id, time) VALUES (?, ?)');
    $stmt->execute([$user_id, $time]);
    
    echo json_encode(['result' => 'success']);
    exit;
}

// 处理获取闹钟请求
if ($_GET['action'] == 'get') {
    $user_id = $_GET['user_id'];
    
    $stmt = $pdo->prepare('SELECT * FROM alarm WHERE user_id = ?');
    $stmt->execute([$user_id]);
    
    $alarms = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($alarms);
    exit;
}

// 处理删除闹钟请求
if ($_GET['action'] == 'delete') {
    $id = $_GET['id'];
    
    $stmt = $pdo->prepare('DELETE FROM alarm WHERE id = ?');
    $stmt->execute([$id]);
    
    echo json_encode(['result' => 'success']);
    exit;
}

?>

Replace "your_database_name", "your_username" and "your_password" in the above code with your actual database name, username and password .

  1. Writing front-end code

Next, we use the WeChat applet development tool to create a new applet project and write the front-end code in it. Create a page named "alarm" and write the following code in its corresponding js file:

// 发送添加闹钟请求
function addAlarm(user_id, time) {
  wx.request({
    url: 'http://your_domain.com/alarm.php?action=add',
    data: {
      user_id: user_id,
      time: time
    },
    success: function(res) {
      console.log(res.data);
    }
  });
}

// 发送获取闹钟请求
function getAlarms(user_id) {
  wx.request({
    url: 'http://your_domain.com/alarm.php?action=get',
    data: {
      user_id: user_id
    },
    success: function(res) {
      console.log(res.data);
    }
  });
}

// 发送删除闹钟请求
function deleteAlarm(id) {
  wx.request({
    url: 'http://your_domain.com/alarm.php?action=delete',
    data: {
      id: id
    },
    success: function(res) {
      console.log(res.data);
    }
  });
}

// 页面加载时发送获取闹钟请求
onLoad: function(options) {
  var user_id = options.user_id;
  getAlarms(user_id);
},

Replace "your_domain.com" in the above code with the actual domain name or IP address.

  1. Complete the alarm clock function

At this point, we have completed the basic back-end interface and front-end code. In the "alarm" page of the mini program, by calling the addAlarm, getAlarms and deleteAlarm functions, you can add, obtain and delete alarm clocks.

In addition, you can also use the timer to realize the alarm reminder function. In the "alarm" page of the mini program, add the following code:

// 监听定时器
setInterval(function() {
  var currentTime = new Date().getTime() / 1000;
  var alarms = this.data.alarms;
  var that = this;

  for (var i = 0; i < alarms.length; i++) {
    if (alarms[i].is_enabled && alarms[i].time <= currentTime) {
      wx.showModal({
        title: '闹钟',
        content: '时间到了!',
        success: function(res) {
          if (res.confirm) {
            deleteAlarm(alarms[i].id);
            getAlarms(that.data.user_id);
          }
        }
      });
      break;
    }
  }
}, 1000);

Through the above code, we can check once every second whether the current time has reached the time set by the alarm clock, and if so, a pop-up window will remind user.

To sum up, the above are the steps and code examples for using PHP to implement the alarm clock function of the WeChat applet. Developers can expand and optimize accordingly according to their own needs and actual conditions. Hope this article helps you!

The above is the detailed content of How to use PHP to implement the alarm clock function of WeChat applet?. 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