[英]PHP & MYSQL Database Insertion Blank
好吧所以我是php,ajax和mysql的新手,我已經搜索了論壇,嘗試了一切,但仍然沒有......我知道這是一個簡單的錯誤但是因為它代表我的代碼是通過我的表單輸入空白信息到數據庫但是當我輸入直接在查詢中它出現在數據庫中的字符串,請幫幫我
PS我知道它可能不是最安全的代碼,但這不是手頭的問題
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注入攻擊,請在查詢中使用它們之前使用預准備語句或轉義變量。 插入時為什么你得空行的原因是:
您在查詢中使用$ _POST數組,同時通過Ajax中的GET請求發送數據:
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);
您從頁面上的相應輸入中獲取主題,收件人和內容變量的位置。
在查詢中使用復選標記:
if(isset($_POST[subject]) && isset($_POST[recipient]) && isset($_POST[content])) {
$sql="INSERT INTO messages (subject, recipient_ids, body)
VALUES
('$_GET[subject]','$_GET[recipient]','$_GET[content]')";
}
並且您沒有在xmlhttp.send();
發送任何數據xmlhttp.send();
您需要發送數據以獲取發布頁面上的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.