我有一个注册表格,表格将在:
这是我的代码:
<input name="uname" type="text" class="form-control" id="uname" placeholder="Username" value="<?php if (!empty($_POST["uname"])) { echo $_POST["uname"]; } else { echo ''; }; ?>" required>
此代码适用于错误提交不清除表单。虽然提交成功,但表单仍然保留表单提交后的数据。因为,我使用这个代码,显然重置按钮也不会起作用。因此,如何在成功提交后清除它?
无论如何,这里是表单验证的代码:
if (isset($_POST['submit'])) {
try {
if ($_POST["pwd"] == $_POST["cpwd"]) {//matched passwords
$stmt = $conn->prepare("INSERT INTO tbl_customers(fld_customer_fname,
fld_customer_lname, fld_customer_gender, fld_customer_phone, fld_customer_email, fld_customer_username, fld_customer_password) VALUES(:fname, :lname,
:gender, :phone, :email, :uname, :pwd)");
$stmt->bindParam(':fname', $fname, PDO::PARAM_STR);
$stmt->bindParam(':lname', $lname, PDO::PARAM_STR);
$stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':uname', $uname, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$uname = $_POST['uname'];
$pwd = $_POST['pwd'];
$stmt->execute();
?>
<br>
<div class="alert alert-success fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Success!</strong> Account created.
</div>
<?php
}
else{//unmatched passwords
?>
<br>
<div class="alert alert-danger fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Error!</strong> Passwords do not match.
</div>
<?php
}
}
答案 0 :(得分:1)
使用Javascript和JQuery,可以使用以下命令:
$(".myform")[0].reset();
使用PHP,您也可以在表单提交到同一页面后重定向(重新加载):
header("location:".$_SERVER['PHP_SELF']);
在PHP中执行此操作的另一种方法是通过存储变量,如下所示:
if(isset($_POST['name']))
{
$post_val=$_POST;
------------------------------------------------------------------------------------------
然后在提交后取消设置$post_val
:
unset($post_val);
只需使用$post_val
<input type="text" name="name" value="<?php echo $_post_val["name"]?>"/>
<input type="text" name="email" value="<?php echo $_post_val["email"]?>"/>
<input type="text" name="phone" value="<?php echo $_post_val["phone"]?>"/>
希望这有帮助!
答案 1 :(得分:0)
我假设您在检查表单字段是否成功后再渲染表单字段。如果我是对的,请将一些$success
变量设置为true
$success = true;
当你取得成功或者在你没有成功的时候。然后在渲染输入中执行:
<input name="uname" type="text" class="form-control" id="uname" placeholder="Username" value="<?php if (!empty($_POST["uname"]) && !$success) { echo $_POST["uname"]; } ?>" required>
ps:你不需要else { echo ''; };
;)