值插入两次mysql

时间:2015-04-05 05:27:10

标签: php mysql ajax

我在这里有一堆代码。我正在尝试聊天

<?php
session_start();
include_once '../db/init.php';

$message = $_GET['message'];
if ($message !== '') {
    //Get sessions ID;
    $uid = $_SESSION['uid'];
    //==========================Insert new message======================//
    $sql = "INSERT INTO `chatbox` (`id`, `user_id`, `message`) VALUES (NULL, '{$uid}', '{$message}');";

    $result = mysqli_query($mysqli, $sql);
    //===========================Retrive Chat List=====================/
    $sql1 = "SELECT * FROM `chatbox` ORDER BY `id` DESC";

    $result1 = mysqli_query($mysqli, $sql1);

    while ($extract = mysqli_fetch_array($result1, MYSQLI_BOTH)) {
        $user_id_new = $extract['user_id'];
        $sql2 = "SELECT * FROM `user` WHERE `id`='$user_id_new' LIMIT 1";
        $result2 = mysqli_query($mysqli, $sql2);
        $row = mysqli_fetch_array($result2, MYSQLI_ASSOC);
        echo $row['name'] . ": " . $extract['message'] . '<br/>';
    }
} else {
    return false;
}

我正在使用Ajax插入这些值并进行检索。

function ajax_chat(){
        if(messageform.message.value == ''){
            alert("Please input some message!");
            return;
        }else{
            var message = messageform.message.value;
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState ==4&& xmlhttp.status == 200){
                    document.getElementById('chat').innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.open('GET', 'message.php?message='+message , true);
            xmlhttp.send();
        }
}

我的问题是,即使我没有用户输入,也会插入值。另一个问题是值被插入两次,即如果我什么也没输入,则在数据库中插入两次空字符串。请帮忙。

0 个答案:

没有答案