创建“更新”MYSQL / PHP页面


Creating an "update" page MYSQL/PHP

我目前正试图通过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);
    }
} 

要回答您的问题,您需要捕获查询的结果并检查其中的错误。

$query = mysql_query(/*query*/);
if (!$query)
    //error handling

请务必阅读SQL注入,正如我的评论。

为了更好地帮助您理解您所看到的行为,我将向您解释您的代码哪里出了问题:

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 似乎未设置。您运行的第一个查询执行得很好,而第二个查询永远无法执行。解决方案:

$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
}

if (!mysql_query($sql,$con))这里没有定义$sql$con。你应该运行mysql_query两次吗?

几个猜测:

  1. 没有mysql connect函数,我假设它在其他地方被调用
  2. 打印查询字符串。我总是发现通过'SELECT * FROM '.%tblvar.';';显式地表示什么是字符串,什么是变量更加调试友好。