每1秒选择最后插入的行

时间:2018-10-01 20:40:19

标签: php mysql

我有2个文件:
1. chat.php:包含聊天消息。
2. loadSingle.php:每1秒钟抓取最后一条新消息。
当我收到最后一条消息时,它总是返回并得到最后一条消息。我想每次都获取没有重复的最后一条消息。

chat.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

<?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();


 }

?>

错误是:每1秒钟获取最后一条消息。每次都没有停下来。我想一次获取最后一条消息,而不循环最后一条消息。谢谢。

2 个答案:

答案 0 :(得分:1)

使用Ajax聊天总是会导致性能下降。您必须考虑使用Web套接字。

有关示例,请参见下面的链接

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

答案 1 :(得分:0)

我不能保证这将是一个固定的代码,但是它将为您提供一个在已经收到的情况下如何在客户端丢弃消息的想法:

客户端:

<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>

服务器端:

<?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();
 }

?>