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();
                    });
                }
            }});
    }

根据您的评论:

我用一种形式调用它。 <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"/>