1
我試圖插入變量到我的數據庫中的表中,由於某種原因,INSERT查詢沒有插入我的值到數據庫中。我已經測試了「test_input」函數,它工作正常,並且我知道連接正在工作,因爲稍後在代碼中的SELECT查詢正在工作。我也知道輸入是在$ _POST superglobal中,所以我認爲它可能與插入查詢有關,通過排除其他可能性。查詢有什麼問題嗎?這裏是我的php代碼:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = test_input($_POST['name']);
$date = test_input($_POST['date']);
$datestring = date('Y-m-d',strtotime(test_input($_POST['date'])));
$venue = test_input($_POST['venue']);
$town = test_input($_POST['town']);
$connection = new mysqli("Example","Example","Example","Example");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_POST != []) {
$connection->query("INSERT INTO events (Name, Date, Venue, Town) VALUES(" . $name . ", " . $datestring . ", " . $venue . ", " . $town . ")");
}
這是我的HTML表單代碼,如果有什麼錯誤的。
<div class="tr" id="addevent">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="td">
<input type="text" name="name">
</div>
<div class="td">
<input type="text" name="date">
</div>
<div class="td">
<input type="text" name="venue">
</div>
<div class="td">
<input type="text" name="town">
</div>
<div class="td">
<input type="submit" value="Add Event">
</div>
</form>
</div>
你可能想檢查你的條件'$ _POST!= []'。也許你可以測試'isset($ _ POST ['name'])'。或者任何其他必須存在的表單參數。在if語句中嘗試echo並查看它是否被執行。 – 2014-11-21 23:21:46
請刪除'$ _SERVER ['PHP_SELF']'作爲你的動作。我知道你有'htmlspecialchars()',但其中任何一個就像黑客天堂。在這裏查看更多信息 - https://phpsecurity.wordpress.com/2007/11/03/the-danger-of-php_self/以及爲什麼htmlspecialchars本身就是一個問題 - http://blog.astrumfutura.com/2012/03/A-旅行者引導到跨站點腳本-XSS-在-PHP-部分-1-如何-未使用的-用htmlspecialchars換輸出轉義/ – DrRoach 2014-11-21 23:24:44