PHP表单更新空值

时间:2016-12-16 11:53:37

标签: php mysql

我一直在尝试使用php表单更改密码。如果我将密码字段留空并仍然单击“提交”,则会将密码更新为空值。

// define variables and set to empty values
$mypassword = $passwordErr = $fid = $fidErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

if(empty($_POST["fid"]))
{
    $fidErr="ID is required";
}
else
{
    $fid=test_input($_POST["fid"]);
}

if(empty($_POST["mypassword"]))
{
    $passwordErr="Password is required";
}
else
{
    $mypassword=test_input($_POST["mypassword"]);
}

}
else
{
echo "plz enter details";
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<body>

<p><span class="error">* required field.</span></p> 

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

<br>Change password<br>

ID:
<input type="number" name="fid" value="<?php echo $fid; ?>">
<span class="error">*<?php echo $fidErr ?></span>
 <br>
Password:
<input type="password" name="mypassword" value="<?php echo $mypassword; ?>">
<span class="error">*<?php echo $passwordErr ?></span>
<br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $fid;
echo "<br>";
echo $mypassword;


$sql = "update faculty set passwd='$mypassword' where fid=$fid";
$result=$conn->query($sql);

if($result==TRUE)
{

    echo "<br> $fid password updated successfully";
}
else
{
    echo "error".$conn->error();
}

即使我已经输入了表单验证码,它仍然会将值更新为空。

1 个答案:

答案 0 :(得分:0)

据我了解,如果密码为空,则需要忽略密码值。试试这段代码:

<?php
echo "<h2>Your Input:</h2>";
echo $fid;
echo "<br>";
echo $mypassword;

if (empty($passwordErr)) {
    $sql = "update faculty set passwd='$mypassword' where fid=$fid";
    $result=$conn->query($sql);

    if($result==TRUE)
    {
        echo "<br> $fid password updated successfully";
    }
    else
    {
        echo "error".$conn->error();
    }
} else {
    echo "The password is not saved because it is empty."
}

UPD:更改了条件,因此它依赖于$ passwordErr值。现在密码空白检查不重复。