我正在尝试通过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);
}
}
答案 0 :(得分:2)
要回答您的问题,您需要捕获查询的结果并检查错误。
$query = mysql_query(/*query*/);
if (!$query)
//error handling
根据我的评论,请务必阅读SQL注入。
答案 1 :(得分:1)
为了更好地帮助您了解您所看到的行为,我会用您的代码向您解释错误:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
第一部分是执行MySQL查询,无论你做了什么不将它的返回值赋给变量。
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
第二部分是尝试通过传递尚未设置的第一个参数$sql
来运行查询,以及第二个参数$con
也< / em>似乎尚未设置。您运行的第一个查询执行得很好,而第二个查询永远不会执行。你的解决方案:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
答案 2 :(得分:0)
if (!mysql_query($sql,$con))
此处$sql
和$con
未定义。你应该两次运行mysql_query
吗?
答案 3 :(得分:0)
几乎没有猜测:
'SELECT * FROM '.%tblvar.';';
的变量是什么,以便更加调试友好。