简体   繁体   English

每 1 秒选择最后插入的行

[英]Select the last inserted row Every 1 second

I have 2 files:我有2个文件:
1. chat.php : contain chat messages. 1. chat.php :包含聊天消息。
2. loadSingle.php : grab last new message every 1 second. 2. loadSingle.php : 每 1 秒抓取最后一条新消息。
When I get the last message it was always return and get the last one.当我收到最后一条消息时,它总是返回并获取最后一条。 I want to get the last message without duplicate every time.我想每次都获得不重复的最后一条消息。

chat.php :聊天.php :

function loadlastmsg(){
var fromIdl = "<?php echo $chat_from_id;?>";
$.ajax({
    type:'POST',
    url:'loadSingle.php',     
    data:{fromIdl: fromIdl,},
    cache: false,
    beforeSend:function(data){

    },
    success: function(data)  
    {
        $('#mainmsgs').append(data);
    }  
});

}

setInterval(function(){
    loadlastmsg();
}, 1000);


</script>
<a href="javascript: loadlastmsg()">Load Last Message</a>

loadSingle.php : loadSingle.php :

<?php
if(isset($_POST["fromIdl"], $_POST["fromIdl"]))
{


    $chat_from_ids = $_POST["fromIdl"];


      require_once 'config/config.php';
      mysqli_set_charset($conn,"utf8mb4");

      $chinbox = array();
      $result=$conn->query("SELECT * FROM chat WHERE id = (SELECT MAX(id) FROM chat WHERE to_id=$userId AND from_id=$chat_from_ids OR to_id=$chat_from_ids AND from_id=$userId) ORDER BY chat.send_date DESC LIMIT 1");
      while ($chinbxsx = mysqli_fetch_assoc($result)) { 
        $chinbox[] = $chinbxsx;
        $from_id =  $chinbxsx['from_id'];
        $subject =  $chinbxsx['subject'];
        $message =  $chinbxsx['message'];
        $get_date = $chinbxsx['send_date'];
        $senddate = date_create($chinbxsx['send_date']);
        $senddate = date_format($senddate, 'Y/m/d H:i:s');

        $from_name = $chinbxsx['from_name'];

        if($from_id != $userId){
          $from_image = $chinbxsx['from_image'];
          $msgclass = 'msgmRec';
        }else{
          $from_image = $userImage;
          $msgclass = 'msgmSend';
        }


      // if($get_date > $get_date){
            echo "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
      // }

      }


    $conn->close();


 }

?>

The mistake is: get the last message every 1 second.错误是:每 1 秒获取最后一条消息。 every time without stop it.每次都没有停下来。 I want to get the last message one time without loop the last message.我想一次获得最后一条消息而不循环最后一条消息。 thanks.谢谢。

Using Ajax for chat will have poor performance always.使用 Ajax 进行聊天总是性能不佳。 You must consider using Web sockets.您必须考虑使用 Web 套接字。

See the below link for a sample请参阅以下链接以获取示例

https://phppot.com/php/simple-php-chat-using-websocket/ https://phppot.com/php/simple-php-chat-using-websocket/

I can't warranty this will be a fixed code, but it will give you the idea of how to discard a message on the client side if already received:我不能保证这将是一个固定的代码,但它会让你知道如何在客户端丢弃已经收到的消息:

CLIENT SIDE:客户端:

<script>

/* Other code ... */

// Global variable for save the latest message ID.
var _latestMessageID = -1;

$(document).ready(function()
{
    // Start getting messages...

    setInterval(
        function() {loadlastmsg();},
        1000
    );
});

function loadlastmsg()
{
    var fromIdl = "<?php echo $chat_from_id;?>";
    var formData = {fromIdl: fromIdl};

    $.ajax({
        type:'POST',
        url:'loadSingle.php',
        data: $.param(formData),
        cache: false,
        success: function(data)
        {
            if (data && data["ID"] > _latestMessageID)
            {
                $('#mainmsgs').append(data["message"]);
                _latestMessageID = data["ID"];
            }
        }
    });
}

</script>

SERVER SIDE:服务器端:

<?php

require_once 'config/config.php';

if(isset($_POST["fromIdl"]) && $_POST["fromIdl"])
{
    $chat_from_ids = $_POST["fromIdl"];
    mysqli_set_charset($conn,"utf8mb4");
    $chinbox = array();

    $result=$conn->query(
        "SELECT *
         FROM chat
         WHERE id = (SELECT MAX(id)
                     FROM chat
                     WHERE (to_id=$userId AND from_id=$chat_from_ids)
                     OR (to_id=$chat_from_ids AND from_id=$userId))
         ORDER BY chat.send_date DESC LIMIT 1"
    );

    // Since the query has LIMIT of 1 this should only loop one time.

    while ($chinbxsx = mysqli_fetch_assoc($result))
    {
        $chinbox[] = $chinbxsx;
        $from_id =  $chinbxsx['from_id'];
        $subject =  $chinbxsx['subject'];
        $message =  $chinbxsx['message'];
        $get_date = $chinbxsx['send_date'];
        $senddate = date_create($chinbxsx['send_date']);
        $senddate = date_format($senddate, 'Y/m/d H:i:s');
        $from_name = $chinbxsx['from_name'];

        if ($from_id != $userId)
        {
            $from_image = $chinbxsx['from_image'];
            $msgclass = 'msgmRec';
        }
        else
        {
            $from_image = $userImage;
            $msgclass = 'msgmSend';
        }

        $msgID = $chinbxsx['id'];
    }

    $returnArray = array();
    $returnArray["ID"] = $msgID;
    $returnArray["message"] = "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";

    echo json_encode($result);    
    $conn->close();
 }

?>

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

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