简体   繁体   English

使用 PHP 和 AJAX 检查数据库更新

[英]Check for a database update using PHP and AJAX

I have a website where when the user clicks a canvas, he draws on it and it gets pushed into the database.我有一个网站,当用户单击 canvas 时,他会使用它并将其推送到数据库中。 And it draws for every user 10 times in one second.它在一秒钟内为每个用户绘制 10 次。

        setInterval(function(){
        $.ajax({
            url: 'data/canvasSave.php',
            success: function(data) {
                $('.result').html(data);
                console.log(data);
                imageCanvas = data;
            }
        });
        let img = new Image();
        img.src = imageCanvas; 
        context.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0 , 0, canvas.width, canvas.height);
    }, 100);
    

Now I notice that this isn't the best way.现在我注意到这不是最好的方法。 But is there a good way to check for Database updates?但是有没有检查数据库更新的好方法? I tried a few if statements but none of them really worked.我尝试了一些 if 语句,但没有一个真正起作用。

You can use PHP sockets for tracking MySQL Database changes with WebSockets.您可以使用PHP sockets通过 WebSockets 跟踪 MySQL 数据库更改。

Setup Frontend设置前端

File: index.php文件:index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MySQL Tracker</title>
 
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.7.4/dist/css/uikit.min.css" />
 
</head>
<body>
  <div class="uk-container uk-padding">
    <h2>Users</h2>
    <p>Tracking users table with WebSockets</p>
    <table  class="uk-table">
      <thead>  
        <tr>
          <th>User ID</th>
          <th>User Name</th>
        </tr>
      </thead>  
    <tbody>  
        <?php
        $connection = mysqli_connect(
            'localhost',
            'root',
            PASSWORD,
            DB_NAME
        );
        $users = mysqli_query($connection, 'SELECT * FROM users');
        while ($user = mysqli_fetch_assoc($users)) {
            echo '<tr>';
            echo '<td>' . $user['id'] . '</td>';
            echo '<td>' . $user['name'] . '</td>';
            echo '</tr>';
        }
        ?>
    </tbody>  
    </table>
    </div>
</body>
</html>

Next, add the PieSocket-JS WebSocket library in your HTML file with the following code:接下来,使用以下代码在 HTML 文件中添加 PieSocket-JS WebSocket 库:

Now, we are ready to connect to the WebSocket channel and start receiving instantaneous updates from the server.现在,我们准备好连接到 WebSocket 频道并开始从服务器接收即时更新。 Add the following code to your index.php file to make a websocket connection.将以下代码添加到您的 index.php 文件以建立 websocket 连接。

<script>
  var piesocket = new PieSocket({
    clusterId: 'CLUSTER_ID',
    apiKey: 'API_KEY'
  });
 
  // Connect to a WebSocket channel
  var channel = piesocket.subscribe("my-channel"); 
  channel.on("open", ()=>{
    console.log("PieSocket Channel Connected!");
  });
 
  //Handle updates from the server
  channel.on('message', function(msg){
    var data = JSON.parse(msg.data);
    if(data.event == "new_user"){
      alert(JSON.stringify(data.data));
    }
  });
</script>

Setup Backend设置后端

Let's create a file called admin.php which adds an entry to the user's table, every time it is visited.让我们创建一个名为 admin.php 的文件,它会在每次访问用户表时添加一个条目。

<?php
$connection = mysqli_connect(
    'localhost',
    'root',
    PASSWORD,
    DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
?>

The code snippet given above adds an entry in the users table every time its execute either via CLI or from a webserver.上面给出的代码片段每次通过 CLI 或从网络服务器执行时都会在用户表中添加一个条目。

Use the following PHP function to do that.使用以下 PHP function 来执行此操作。

<?php
function publishUser($event){
  $curl = curl_init();
 
  $post_fields = [
    "key" => "PIESOCKET_API_KEY", 
    "secret" => "PIESOCKET_API_SECRET",
    "channelId" => "my-channel",
    "message" => $event
  ];
 
  curl_setopt_array($curl, array(
    CURLOPT_URL => "https://PIESOCKET_CLUTER_ID.piesocket.com/api/publish",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($post_fields),
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json"
    ),
  ));
 
  $response = curl_exec($curl);
  print_r($response);
}
 
$connection = mysqli_connect(
    'localhost',
    'root',
    PASSWORD,
    DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
$payload = json_encode([
  "event" => "new_user",
  "data" => [
  "id"=> 1, 
  "name"=>"Test user"]
]);
 
publishUser($payload);
?>

Track MySQL changes in real-time with Laravel使用 Laravel 实时跟踪 MySQL 变化

For example, in your User model under app/model/User.php add the following code block例如,在 app/model/User.php 下的用户 model 中添加以下代码块

public static function boot() {
    parent::boot();
 
    static::created(function($user) {
        publishUser(json_encode($user));
    });
}

Track MySQL changes in real-time with Django使用 Django 实时跟踪 MySQL 变化

import requests
import json
url = "https://CLUSTER_ID.piesocket.com/api/publish"
payload = json.dumps({
    "key": "API_KEY", 
    "secret": "API_SECRET",
    "channelId": 1,
    "message": { "text": "Hello world!" }
});
headers = {
  'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM