2016-12-16 56 views
-1

我一直在嘗試使用php窗體來更改密碼。如果我將密碼字段留空並仍然單擊提交,它會將密碼更新爲空值。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(); 
} 

即使我已經把表單驗證代碼,它仍然更新值爲空。

+0

即使您的輸入爲空,您也總是「更新」它。 – Federkun

+0

爲什麼你在下面寫代碼,在成功條件下寫更新代碼 – rahulsm

+0

認證系統*真的*我的意思*真的*不是你應該從頭開發的系統。使用一個久經考驗的 – e4c5

回答

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值。現在密碼空白檢查不重複。

+0

謝謝。但是這個說法呢? –

+0

if(empty($ _POST [「mypassword」]))//這一個 { $ passwordErr =「需要密碼」; } –

+0

我剛剛更新了我的答案。你是對的,你提到的條件已經做了檢查。順便說一句,如果您嘗試將零或一組零作爲密碼保存,代碼將無法按預期工作。 –