繁体   English   中英

创建一个“更新”页面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连接功能我认为它在其他地方被调用
  2. 打印出您的查询字符串。 我总是发现可以通过'SELECT * FROM '.%tblvar.';';明确表示什么是字符串,什么是变量'SELECT * FROM '.%tblvar.';'; 更加调试友好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM