我有一个简单的表单,通过POST消息将数据发送到服务器。但是,我收到了错误#34;无法执行查询"每当我点击提交按钮。这是我的实施:
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);
获取一些示例数据,这就是我得到的:
array(2){[&#34; email&#34;] =&gt; string(11)&#34; abc@abc.com" [&#34;注释&#34;] =&GT; string(5)&#34;你好&#34;无法执行查询
答案 0 :(得分:1)
您缺少任务操作员。您没有正确发送名称,这就是查询失败的原因。
尝试使用
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注入的直接方式。