Skip to content
Advertisement

How to display error message with php after form submit

Hello everyone i am building a project with php where do i want to display error message on form submit with php but the problem is i am unable to do that my page gets reloads and the message doesnot shows. Below i am pasting the codes please help me how to do that.

Form part

<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 codes

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');
    }
    
    
    
}

Advertisement

Answer

you can use with session like this

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 is secure and every time you post it will set session and then it will remove the value set is session with unset the session.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement