PHP 即时通讯工具

PHP Instant messenger

我正在尝试使用 PHP 和 SQL 创建一个 Messenger 这是我的代码

    <form action="send_post.php" method="post">
    <h3>Name:</h3>
    <input type="text" name="name">
    <h3>Message:</h3>
    <input type="text" name="message">
    <input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                while(1){
                        ob_start();
                        echo "" . $row["name"]. " - " . $row["message"]. "<br>";

                        sleep(10);
                        echo "" . $row["name"]. " - " . $row["message"]. "<br>";
                        ob_end_clean();

}
} 
}


$conn->close();
?>

然而这不起作用,有什么原因吗? 一旦我添加无限 while 循环来刷新消息,问题就开始了。

PHP 在服务器端工作,这意味着客户端(来宾)请求一个页面,服务器然后 "compiles" 然后将其作为客户端语言发送给客户端,例如 HTML .如果 PHP 代码从未达到 end/stop 客户端浏览器将认为服务器停止响应并给出错误。

要实现您正在尝试做的事情,您可能需要研究类似 JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX

的内容

更新你可以看看这个blogpost来了解我在说什么。