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

时间:2019-01-09 18:05:25

标签: javascript php html css mysql

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

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

1 个答案:

答案 0 :(得分:0)

当您的前端(HTML,CSS)和后端(PHP和MySQL / PDO查询)在同一页面上时,会发生这种情况。更好的是,您可以使用前端插入详细信息,并将其发送到其他PHP文件中的后端,然后通过ajax / header / cookies等将结果状态重定向到前端文件。