Skip to content
Advertisement

How to validate two forms at once with php

I have two forms contained in one PHP file. One of the forms is for “log in” and the other form is to “sign up” i have some CSS and JS that will switch out the forms visually, but regardless the two forms are still in one php file.

These forms are standard:

<form action="login.php" method="post" name="user-sign-up">
 <div class="error">
<?php if(!empty($error)){echo $error;} ?>
</div>
          <span>First name</span>
          <input type="text" name="fname" class="fname">
        <input type="submit" value="Sign Up" class="signupdawg" id="firstname-signup"> 
</form>

Then I got another form underneath that one.

Here’s my php, it sort of works and only works for one of the forms:

if( isset($_POST['fname']) && !empty($_POST['fname'])){

    $upName = $_POST['fname'];

if(empty($upName)){

        $error = 'All fields are required';

I only shortened the code, so it wouldn’t take up to much space. I had other inputs like a password, but I just removed it because the code is pretty much the same except I had an “or” in my php empty check and a few more lines in my html for it.

Anyway, I am wondering how I can validate two forms at once with PHP.

Thank you.

Advertisement

Answer

You can only submit one form at a time, so you need to use something on the form to determine which one was submitted. This is just a simple example using your code:

if(isset($_POST['Sign_Up'])) {
    //do sign up stuff
} 
elseif(isset($_POST['Login'])) {
    //do login stuff
}

Notice Sign Up is converted to Sign_Up. It may be better to use two separate action in each form and have two different files.

Additionally, isset is redundant here:

if( isset($_POST['fname']) && !empty($_POST['fname'])){

The empty already checks if it is set, so just:

if(!empty($_POST['fname'])){
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement