【问题标题】:How to fetch data every second from MYSQL database如何从 MYSQL 数据库中每秒获取数据
【发布时间】:2021-11-08 01:52:24
【问题描述】:

我正在尝试使用 HTML、CSS、JS、PHP 和 Mysql 制作一个 聊天应用程序
我已经完成了所有功能,包括发送消息、接收消息、显示用户... 但我面临的问题是每次我都需要刷新页面收到一条新消息

我正在寻找一种使用 mysql 数据库中的新数据自动更新数据的方法。
代码:

<?php    
if ($_GET['id']){
        $id = $_GET['id'];
        $id = preg_replace("/[^0-9]/", "", $id);
        $fetching_messages = "SELECT * FROM users_messages WHERE from_user='$id' OR to_user='$id' ORDER BY id";
        $check_fetching_messages = $db->prepare($fetching_messages);
        $check_fetching_messages->execute();
        $messages_all = $check_fetching_messages->fetchAll();
    
      } else {
      }
?>

<div id="autodata">
        <?php foreach($to_users as $to_user) : ?>
          <?php
          $to_user_id = $to_user['to_user'];
          $to_user_name = "SELECT * FROM users_accounts WHERE id='$to_user_id'";
          $check_to_user_name = $db->query($to_user_name);

          while ($row_to_user_name = $check_to_user_name->fetch()) {
              $id_user = $row_to_user_name['id'];
              $username = $row_to_user_name['username'];
              $pdp = $row_to_user_name['profile_image'];

          }

          if ($id_user == $user_id){

          } else {
            echo '
            <form style="height: fit-content;" name="goto'.$to_user_id.'" action="inbox.php">
              <div onclick="window.location.replace('."'".'?id='.$to_user_id."'".')" class="inbox_chat_field_user">';
                if (empty($pdp)){
                  echo "<img class='inbox_chat_field_user_img' src='uploads\profile\default.jpg'/>";
                } else {
                echo "<img class='inbox_chat_field_user_img' src='".$pdp."'/>";
              }
              echo '
              <span class="inbox_chat_field_user_p">'.$username.'</span>
            </div>
          </form>
             <hr class="inbox_separing_hr">';
          }

          ?>

       <?php endforeach;?>
</div>

【问题讨论】:

    标签: php mysql ajax fetch


    【解决方案1】:

    只是你不能这样做,PHP 是一种服务器端语言,你不能告诉客户端从 PHP 刷新。

    要完成聊天,您应该考虑在浏览器中使用 JavaScript。

    最简单的方法是向您的服务器发送一个 AJAX 请求,并每隔 5 或 10 秒检查一次是否有新消息,然后对响应中的消息执行您想要的操作。

    如果您在应用程序中使用 jquery,您可以通过这种方式发送 ajax 请求:

    $.get( "messages.php", function( data ) {
      console.log( "Data Loaded: " + data );
    });
    

    messages.php 脚本中,您可以从数据库中获取新消息并以 HTML 或 JSON 格式返回

    您也可以使用firebase提供的FCM服务将您的消息直接推送到客户端,请查看this PHP FCM包。

    还有其他解决方案,例如 websockets 等...

    【讨论】:

      【解决方案2】:

      如果您将业务逻辑与表示分离,我直接更新您的代码会更容易,所以我不会尝试这样做。相反,我将描述一种您可以使用的技术,并留给您找出使用它的最佳方法。您可以考虑使用服务器发送的事件。请参阅 JavaScript 类 EventSource

      以下“业务逻辑”PHP 程序sse_cgi.php 每 2 秒定期有新的输出(总共 5 次)。在这种情况下,输出只是作为字符串的当前日期和时间。但它可能是例如 JSON 记录。注意它输出的特殊标题:

      <?php
      header("Content-Type: text/event-stream");
      
      $firstTime = True;
      for ($i = 0; $i < 5; $i++) {
          if (connection_aborted()) {
              break;
          }
      
          $curDate = date(DATE_ISO8601);
          echo 'data: This is a message at time ' . $curDate, "\n\n";
      
          // flush the output buffer and send echoed messages to the browser
          while (ob_get_level() > 0) {
              ob_end_flush();
          }
          flush();
          if ($i < 4) {
              sleep(2); # Sleep for 2 seconds
          }
      }
      

      这是要输出的演示 HTML。在这种情况下,JavaScript 代码只是用更新的值替换旧日期。它也可以将新的&lt;li&gt; 元素附加到现有的&lt;ul&gt; 标签或将&lt;tr&gt; 元素附加到现有的&lt;table&gt;

      <html>
      <head>
         <meta charset="UTF-8">
         <title>Server-sent events demo</title>
      </head>
      <body>
        <div id='date'></div>
      
      <script>
        var evtSource = new EventSource('sse_cgi.php');
        var date = document.getElementById('date');
      
        evtSource.onmessage = function(e) {
            // replace old content
            date.innerHTML = e.data;
        };
      
        evtSource.onerror = function() {
            // occurs when script terminates:
            evtSource.close();
            console.log('Done!');
        };
      
      </script>
      </body>
      </html>
      

      请注意,此演示文稿引用了返回连续日期的“业务逻辑”脚本。

      重要提示

      重要的是要认识到,这种技术会在所有数据最终发送完毕并且业务逻辑脚本最终终止(或在浏览器中运行的演示文稿发出对 @987654329 的调用之前)的持续时间内保持与服务器的连接打开。 @ 关闭连接)。因此,如果您有很多同时用户,这可能是个问题。

      如果您的应用程序没有有限数量的要返回的消息,则可以通过让业务逻辑脚本在发送一条消息后立即返回来克服前面描述的问题。这将中断与浏览器的连接,如果浏览器仍然存在,则会自动尝试重新连接业务逻辑脚本(请注意,此重新连接可能需要一段时间):

      更新的业务逻辑

      <?php
      header("Content-Type: text/event-stream");
      
      # Simulate waiting for next message:
      sleep(2);
      $curDate = date(DATE_ISO8601);
      echo 'data: This is a message at time ' . $curDate, "\n\n";
      
      // flush the output buffer and send echoed messages to the browser
      while (ob_get_level() > 0) {
          ob_end_flush();
      }
      flush();
      

      更新的演示文稿

      <html>
      <head>
         <meta charset="UTF-8">
         <title>Server-sent events demo</title>
      </head>
      <body>
        <div id='date'></div>
      
      <script>
        var evtSource = new EventSource('sse_cgi.php');
        var date = document.getElementById('date');
      
        evtSource.onmessage = function(e) {
            // replace old content
            date.innerHTML = e.data;
        };
      
      </script>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 1970-01-01
        • 2021-12-21
        • 2015-07-23
        • 2015-08-17
        • 1970-01-01
        • 2017-12-07
        • 1970-01-01
        相关资源
        最近更新 更多