gpt4 book ai didi

php - 验证后为什么我的表单数据被清除

转载 作者:行者123 更新时间:2023-11-29 13:16:34 24 4
gpt4 key购买 nike

我正在对我的 html 值进行 PHP 验证。但是当 PHP 验证时失败,我返回页面,表单数据被清除。无论如何,有没有办法在 php 中保存并重新加载表单数据

php中的验证代码

<?php
$firstname=$lastname=$contactno="";
$firstnameErr=$lastnameErr=$contactnoErr="";

if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;

/*FirstName Validation starts here*/
if(empty($_POST["fname"]))
{
$firstnameErr="*firstname is Required";
$valid=false;
}
else
{
$firstname=test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "&nbsp;&nbsp;Only letters and white space allowed";
$valid=false;
}
}
/*FirstName Validation Ends here*/

/*lastName Validation starts here*/
if(empty($_POST["lname"]))
{
$lastnameErr="*lastname is required";
$valid=false;
}
else
{
$lastname=test_input($_POST["lname"]);
if(!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "&nbsp;&nbsp;Only letters and white space allowed";
$valid=false;
}
}
/*LastName Validation Ends here*/

/*Contact No Validation starts here*/
if(empty($_POST["contact"]))
{
$contactnoErr="*Contact No. is required";
$valid=false;
}
else
{
$contactno=test_input($_POST["contact"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$contactno))
{
$contactnoErr="*Enter a valid contact no";
$valid=false;
}
}
/*Contact No Validation Ends here*/

//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}

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

?>

表单

<form method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Firstname<span class="error">*</span>:</label>
<input type="text" name="fname"/>
<span class="error"><?php echo $firstnameErr?></span><br />
<br />
<label>lastname<span class="error">*</span>:</label>
<input type="text" name="lname"/>
<span class="error"><?php echo $lastnameErr?></span><br />
<br />
<label>contactno<span class="error">*</span>:</label>
<input type="text" name="contact"/>
<span class="error"><?php echo $contactnoErr?></span>
<br />
<input style="margin:20px 20px 20px 250px;" type="submit" name="Submit" value="Submit"/>
</form>

最佳答案

您正在加载一个新表单(即使它与上次加载的表单相同),并且您的任何输入都没有 value 属性。

关于php - 验证后为什么我的表单数据被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com