我目前正在嘗試通過PHP,它允許用戶更新我的數據庫中的數據的頁面。我遇到了兩個問題:首先,當我運行我的代碼時,出現「錯誤:查詢爲空」,但是對數據庫進行了更新,這導致我遇到了第二個問題。更新完成後,留空的字段(如果用戶不需要將數據輸入所有字段(如果只有一兩個要更新的話)將變爲空白。這是因爲我當前的腳本更新了所有的元素,但是有什麼辦法可以讓我把它放在哪裏如果用戶把輸入字段留空,當數據庫更新時什麼都不會改變?創建一個「更新」頁面MYSQL/PHP
這裏是我的代碼:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
這無關你的問題,但你的腳本很容易受到一個非常危險的漏洞被稱爲[SQL注入(http://en.wikipedia.org/wiki/SQL_injection)。只是想確保你知道並瞭解到這一點。 –