[英]How to display error message with php after form submit
大家好,我正在用 php 構建一個項目,我想在使用 php 提交的表單上顯示錯誤消息,但問題是我無法做到我的頁面重新加載並且消息不顯示。 下面我粘貼代碼,請幫助我如何做到這一點。
表格部分
<form method="post" action="" id="contact_form">
<div class="form-row mt-3">
<div class="col">
<div class="form-group input-group">
<input type="text" class="form-control" name="con_first_name" placeholder="Enter your first name">
<span><?php echo $err_fname; ?></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" name="con_submit" class="btn show_more con_submit">Submit</button>
</div>
</form>
php代碼
if(isset($_POST['con_submit'])){
// Posted form data
if(!empty($_POST['con_first_name'])){
$err_fname = "First name cannot be empty";
}else{
$fname = htmlentities(strip_tags(mysqli_real_escape_string($con, $_POST['con_first_name'])), ENT_QUOTES, 'UTF-8');
}
}
我會用會話來做!
session_start();
if(isset($_POST['con_submit'])){
// Posted form data
if(!empty($_POST['con_first_name'])){
$err_fname = "First name cannot be empty";
$_SESSION['form_error'] = $err_fname;
}else{
$fname = htmlentities(strip_tags(mysqli_real_escape_string($con, $_POST['con_first_name'])), ENT_QUOTES, 'UTF-8');
}
}
然后你想展示它的地方:
if(isset($_SESSION['form_error'])){
echo $_SESSION['form_error'];
unset($_SESSION['form_error']);
}
使用此代碼
if(isset($_POST['con_submit'])){
if(empty($_POST['con_first_name'])){
$err_fname = "First name cannot be empty";
}else{
$fname = htmlentities(strip_tags(mysqli_real_escape_string($con, $_POST['con_first_name'])), ENT_QUOTES, 'UTF-8');
}
}
你可以像這樣使用會話
session_start();
if(isset($_POST['con_submit'])){
// Posted form data
if(empty($_POST['con_first_name'])){
$err_fname = "First name cannot be empty";
$_SESSION['form_error_name'] = $err_fname;
}else{
$fname = htmlentities(strip_tags(mysqli_real_escape_string($con, $_POST['con_first_name'])), ENT_QUOTES, 'UTF-8');
}
}
if(isset($_SESSION['form_error_name'])){
echo $_SESSION['form_error_name'];
unset($_SESSION['form_error_name']);
}
session 是安全的,每次發布它都會設置 session,然后它將刪除設置為 session 的值並取消設置 session。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.