HTTP POST请求问题


HTTP POST Request Problems

我有一个简单的表单,通过POST消息向服务器发送数据。然而,我得到的错误"无法执行查询"每当我点击提交按钮。下面是我的实现:

sample . html

<!DOCTYPE html>
<html>
<head>
<script>
        function pullMore(){
            var xmlhttp;
            if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome,etc.
                xmlhttp = new XMLHttpRequest();
            }else{ // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    document.getElementById("news_mesgs").innerHTML = xmlhttp.responseText;
                }
            }
            var name = document.getElementById("name");
            var email = document.getElementById("email");
            var comments = document.getElementById("comment");
            var parameters="name"+name.value+"&email="+email.value+"&comments="+comments.value;
            xmlhttp.open("POST", "reviews.php", true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(parameters);
        }
</script>
</head>
<body style="background-color : #e9e9e9;">
<div> Hello there </div>
<form>
    Name: <input type="text" id="name" name="name">
    Comment: <input type="text" id="comment" name="comment">
    Email: <input type="text" id="email" name="email">
    <input type="button" value="Submit" onclick="pullMore()">
</form>

<div id="news_mesgs"> come here </div>
</body>
</html>

reviews.php

mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");

$query = 'INSERT INTO Reviews (Name, Email, Review) VALUES ('.$_POST['name'].','.$_POST['email'].','.$_POST['comments'].');';
$result = mysql_query($query) or die( "Unable to execute query");

更新:由于某种原因,$_POST["name"]显示为空。我试图print var_dump($_POST);一些样本数据,这就是我得到的:数组(2){["email"]=>字符串(11)"abc@abc.com" ["comments"]=> string(5)无法执行查询

您缺少赋值操作符。您没有正确发送名称,这就是为什么查询失败的原因。

尝试使用

var parameters="name="+name.value+"&email="+email.value+"&comments="+comments.value;

您还缺少引号。使用

$query = 'INSERT INTO Reviews (Name, Email, Review) VALUES ("'.$_POST['name'].'","'.$_POST['email'].'","'.$_POST['comments'].'");';

或者稍微好一点

$query = 'INSERT INTO Reviews (Name, Email, Review) VALUES ("'.mysql_escape_string($_POST['name']).'","'.mysql_escape_string($_POST['email']).'","'.mysql_escape_string($_POST['comments']).'");';

不要只是在查询中插入post变量。这是SQL注入的直接方式。

检查如何在PHP中防止sql注入?