我有一個PHP腳本,並插入部分如下(我知道,沒有PDO或mysqli的,這只是我個人的測試):用戶輸入插入DB通過AJAX導致空字段
<?php
$user = $_POST['user'];
$comments = $_POST['comment'];
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db('localh',$con);
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comments')");
if(!$query){die(mysql_error());}
mysql_close($con);
?>
如果我在表單動作中使用此腳本,它將正常工作,輸入值將被添加到數據庫中。
這裏的形式:
<form>
<p>User: <input type="text" id="user" /></p>
<p>Comment:<input type="text" id="comment" /></p>
<input type="button" id="submit" onClick="insertData();" />
</form>
而AJAX的一部分,位於頭部標籤之間:
function insertData(){
var ajaxRequest = new XMLHttpRequest();
var usr = document.getElementById("user").value;
var cmnt = document.getElementById("comment").value;
ajaxRequest.open("POST", "insert.php", true);
ajaxRequest.send(usr, cmnt);
}
其結果將是數據庫中的空行。我不知道這是爲什麼,我無能爲力。
只要你知道,請確保您使用它負責任。我將這篇評論發佈給將來的訪問者:[**請不要在新代碼中使用'mysql_ *'函數**](http://bit.ly/phpmsql)。他們不再被維護,[棄用過程](http://j.mp/Rj2iVR)已經開始。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –
不要忘記主要的sqli漏洞。 –
我不知道人們是否認真閱讀了這個通知......我祈禱他們這樣做。 – itachi