为什么这个程序每次重新加载页面时都要在消息表中插入值?

8iwquhpp  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(254)

这是一个使用php、mysql、html、css和javascript的简单聊天系统的代码。这段代码的问题是,每当用户输入一条消息并按下send按钮时,消息就会被发送,并且值会被插入到消息表中,但是当我们刷新页面时,同样的消息会再次出现,并且消息会再次被插入到数据库中。我试过管理架构,但问题没有解决。这是我的密码。

<html>
<head>
<link rel="stylesheet" type="text/css" href="chat.css">
</link>

</head> 
<body>
<?php
session_start();
include 'ConnectionPDO.php';
//include_once 'chat.html';
$_SESSION["person"]=$_GET["person"];
if(isset($_SESSION['username'])){ 

if(isset($_POST['btn'])){
     $message=$_POST['msg'];
     $person=$_GET['person'];   
    try {
    $stmt = $dbh->prepare("INSERT INTO `messages` (`id`, `sendby`, `sento`, `date/time`, `seen`, `active`, `message`) VALUES (NULL, ?, ?, CURRENT_TIMESTAMP, 'No', 'No', ?)");
    $stmt->bindParam(1,$_SESSION['username']);
    $stmt->bindParam(2,$person);
    $stmt->bindParam(3,$message);
    $stmt->execute();
        if($stmt) {
            echo "<br>";
            echo "Message sent!";
        }
    }
    catch (PDOException $e) {
        echo $e->getMessage(); 
    } 

    }
}else{

}
?>

<div id="main">
<div id="inbox" style="height:400px;overflow:scroll"> 

<?php
$_SESSION["person"]=$_GET["person"];

try {
        $stmt2 = $dbh->prepare("select * from `messages` where (`sendby`=? AND `sento`=?) OR (`sendby`=? AND `sento`=?)");
        $stmt2->bindParam(1, $_SESSION['username']);
        $stmt2->bindParam(2, $_SESSION["person"]);
        $stmt2->bindParam(3, $_SESSION["person"]); 
        $stmt2->bindParam(4, $_SESSION['username']);
        $stmt2->execute();

        while($row=$stmt2->fetch()) {
         $sento= $row['sendby']; 
         $message= $row['message']; 
         $time= $row['date/time']; 
         echo $sento;
        echo "<br>";
        echo $message;
        echo "<br>";
        echo $time;
        echo "<br>"; 
        echo "<hr>";
        }
    } 
    catch (PDOException $e) {
        echo $e->getMessage(); 
    }

?>

</div>

<form method="post">
<input type="text" name="msg" placeholder="Enter your message here" id="msg"><br>
<input type="submit" value="Send" name="btn" id="btn">
</form>
</div>

<script> 
setInterval(myFunction,1000);
function myFunction(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("inbox").innerHTML = this.responseText;
        }
    };
    xhttp.open("POST","sendMsg.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send();
}
</script>

</body>
</html>
jmo0nnb3

jmo0nnb31#

当前端(html、css)和后端(php和mysql/pdo查询)位于同一页面上时,就会发生这种情况。更好的是,您可以使用前端插入详细信息并将其发送到其他php文件中的后端,并通过ajax/header/cookies等将结果状态重定向到前端文件。

相关问题