SQL 查询正在生成多条记录

SQL query is making multiple records

<?php

    $msg = $_POST['postmsg'];

    $con = mysqli_connect("localhost","root","somerset","chatroom") or die("sqlffs");

    mysqli_query($con, "INSERT INTO `chat`(`msg`) VALUES ('$msg')");
    mysqli_close();

?>

我的代码在我的数据库中创建了多条记录。 我不明白为什么会这样。

这是运行 php

的代码
       function sendmsg(){
 $(document).keypress(function(e) {
            if(e.which == 13) {

                var message = $('#msgstring').val();
                //$('#show').html(message);
                if(message !="")
                {
                    $.post('sendmessage.php',{postmsg:message},
                    function(data){
                     exit();

                    });
                }

            }});
    }

根据您的评论:

I call it in in a form. <input onkeypress="return event.keyCode != 13;" type="text" onkeyup="sendmsg()" id="msgstring"/>

发生的情况是您不止一次调用此函数:

sendmsg()

这个函数有什么作用?它绑定了一个 keypress 事件:

$(document).keypress(function(e) {
    // handle the event
});

也就是说,它不处理事件。它绑定了处理事件的代码。因此,每次调用 sendmsg() 时,都会创建一个重复绑定。考虑以下事件序列:

  1. 调用sendmsg(),绑定keypress事件
  2. 按下 键,POST请求创建一条记录。
  3. 再次调用sendmsg(),绑定一个keypress事件
  4. 再次按下一个键,两个个事件处理程序被执行,因此,两个 POST个请求被执行并且创建了两条条记录。
  5. 等等...

每次您在 input 中按下一个键,都会触发该事件,但您 创建了一个重复的事件处理程序。所以每次按键都会导致越来越多的事件处理程序,并且会创建越来越多的记录。

只绑定一次事件处理器:

// not inside a function
$(document).keypress(function(e) {
    // handle the event
});

然后,只要您在 input 中按下某个键,您就会自动调用此事件处理程序。所以你不需要在 input:

中重复代码
<input type="text" id="msgstring"/>