好的,所以我对php、ajax和mysql还不太熟悉,我在论坛上搜索了所有东西,但还是没有找到。我知道这是一个简单的错误,但就目前的情况来看,我的代码是通过表单向数据库输入空信息,但当我直接在查询中键入字符串时,它就会出现在数据库中,请帮助我
我知道这可能不是最安全的代码,但这不是问题所在
function message(){
alert("You are about to compose a message");
var stuff=[
'<div id ="compose_window">',
'<div id="new_message">',
'<div id="header"><strong> New Message </strong></div>',
'</div>',
'<form action="" method= "post">',
'<fieldset>',
'<strong>To</strong><br> <input type="text" id ="recipient" name="recipient" class="textfield"> <br>',
'<strong>Subject</strong><br> <input type="text" id="subject" name="subject" class="textfield"> <br><br>',
'<strong>Message</strong><br> <textarea id = "content" name="content" cols="40" rows="5"></textarea> <br>',
'<button id="send" type="button" onclick= loadXMLDoc()> <strong> Send </strong> </button>',
'</fieldset>',
'</form>',
'</div>',
'<div id="Response"></div>',
].join('');
document.getElementById("area").innerHTML= stuff;
}
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","send.php",true);
xmlhttp.send();
}
这是用于插入的php
<?php
$con=mysqli_connect("127.9.52.129","boballen","","cheapomail");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO messages (subject, recipient_ids, body)
VALUES
('$_POST[subject]','$_POST[recipient]','$_POST[content]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Message Sent 1 record added";
mysqli_close($con);
?>
最佳答案
您的代码易受SQL注入攻击,请在查询中使用准备好的语句或转义变量。插入时出现空行的原因是:
在Ajax中通过GET请求发送数据时,您正在查询中使用$\u POST数组:
xmlhttp.open("GET","send.php",true);
使用$GET而不是$POST:
$sql = "INSERT INTO messages (subject, recipient_ids, body)
VALUES (?,?,?)";
if ($stmt = $mysqli->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("sss", $_GET['subject'],$_GET['recipient'],
$_GET['content']);
/* execute query */
$stmt->execute();
}
阿贾克斯
您也不会在Ajax请求中发送GET参数。尝试添加它们,使用如下方法:
subject = encodeURIComponent(document.getElementById("subject").value);
recipient = encodeURIComponent(document.getElementById("recipient").value);
content = encodeURIComponent(document.getElementById("content").value);
xmlhttp.open("GET","send.php?subject=" + subject + "&recipient="
+ recipient + "&content=" + content,true);
从页面上的适当输入获取主题、收件人和内容变量的位置。