升级我的PHP聊天系统? (仅限更新新消息?)

时间:2018-03-08 21:45:21

标签: javascript php jquery ajax

JS:

"use strict";

$(document).ready(function () {
    var chatInterval = 250; //refresh interval in ms
    var $userName = $("#userName");
    var $chatOutput = $("#chatOutput");
    var $chatInput = $("#chatInput");
    var $chatSend = $("#chatSend");

    function sendMessage() {
        var userNameString = $userName.val();
        var chatInputString = $chatInput.val();

        $.get("./write.php", {
            username: userNameString,
            text: chatInputString
        });

        $userName.val("");
        retrieveMessages();
    }

    function retrieveMessages() {
        $.get("./read.php", function (data) {
            $chatOutput.html(data); //Paste content into chat output
        });
    }


    $chatSend.click(function () {
        sendMessage();
    });

    setInterval(function () {
        retrieveMessages();
    }, chatInterval);
});

Write.php:

<?php
require("connect.php");

//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
    //if the connection to the db failed
    echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}


//get userinput from url
$username=substr($_GET["username"], 0, 32);
$text=substr($_GET["text"], 0, 128);
//escaping is extremely important to avoid injections!
$nameEscaped = htmlentities(mysqli_real_escape_string($db,$username)); //escape username and limit it to 32 chars
$textEscaped = htmlentities(mysqli_real_escape_string($db, $text)); //escape text and limit it to 128 chars



//create query
$query="INSERT INTO chat (username, text) VALUES ('$nameEscaped', '$textEscaped')";
//execute query
if ($db->real_query($query)) {
    //If the query was successful
    echo "Wrote message to db";
}else{
    //If the query was NOT successful
    echo "An error occured";
    echo $db->errno;
}

$db->close();
?>

Read.php

<?php
require("connect.php");

//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name); 
if ($db->connect_errno) {
    //if the connection to the db failed
    echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}


$query="SELECT * FROM chat ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
    //If the query was successful
    $res = $db->use_result();

    while ($row = $res->fetch_assoc()) {
        $username=$row["username"];
        $text=$row["text"];
        $time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#

        echo "<p>$time | $username: $text</p>\n";
    }
}else{
    //If the query was NOT successful
    echo "An error occured";
    echo $db->errno;
}

$db->close();
?>

基本上一切都很完美,除了我想让人们复制和粘贴,但是目前脚本正在做的是更新聊天区间的每条消息,即250MS。

如何制作,以便突出显示信息并复制?

所以我的问题是,我可以这样做:

我可以让它只更新每250-500MS出现的新消息,而不是更新HTML的每一个部分,因为这会浪费资源(特别是如果有很多消息)

我希望你能帮忙!

P.S。我不想使用网络套接字

2 个答案:

答案 0 :(得分:2)

要从最后一条消息开始更新,请获取最后一条消息的ID,然后在下一个$.get中包含该消息的ID,并仅获取之后发送的消息。

然后在你的javascript中使用.append(),这样你就不会覆盖整个事情。

答案 1 :(得分:0)

看起来你已经在使用jQuery了。您可以创建一个PHP脚本,该脚本仅查询数据库以查找比最新显示的条目更新的条目,然后使用$.append将消息附加到保存它的<div>(或其他任何元素)。

此外,正如评论者指出的那样,您仍然可能会受到SQL注入的影响。考虑将PDOprepared SQL statements一起使用。