1
votes

I am working on making a PHP and MySQL application for practicing my new-found love for programming. I have a login script; the HTML form is as follows:

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">

            Username:

                <input type="text" name="username" maxlength="60"><br />



            Password:

                <input type="password" name="password" maxlength="60"><br />



           Confirm Password:

                <input type="password" name="password_confirm" maxlength="60"><br />


                <input type="submit" name="submit" value="Register"><br />

         </form>

This continues into the PHP form validator:

<?php

$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];

       //This makes sure they did not leave any fields blank 

function FieldComplete($user, $password, $password_confirm) {
    if (!isset($user, $password, $password_confirm) &&
        $user && $password && $password_confirm == "" || " ") {
        $field_confirm = false;
    } else {
        $field_confirm = true;
    }


    if ($field_confirm == true) {
        echo "";
    } else {
        echo "You did not complete all the required fields.";
    }
}

FieldComplete($username_original, $password_original, $password_confirm_original);

?>

I realize that making a function for this might seem a little useless, but it was as close as I got to the result I wanted.

However, this code displays the error "You did not complete all the required fields." on loading of the page. I only want that error to display if they have pressed the register button and still have a blank field.

Any advice or help is greatly appreciated. Thanks StackOverflow community!

2

2 Answers

4
votes

If you want to run the php code only if button is submitted so you need to check about that at the top of your page

if(isset($_POST["submit"]))
{
   //form has been submitted
   //do validation and database operation and whatever you need
} else {
  //form has not been submitted
  //print the form
}
1
votes

In addition to Fabio answer, you can improve your code like this:

if(isset($_POST['submit'])){
    $username_original = $_POST["username"];
    $password_original = $_POST["password"];
    $password_confirm_original = $_POST["password_confirm"];

    $isComplete = FieldComplete($username_original, $password_original, $password_confirm_original);
    if(!$isComplete){
       echo "You did not complete all the required fields.";
    }
}else{
//display the form

}



function FieldComplete($user, $password, $password_confirm) {
    if (!isset($user, $password, $password_confirm) &&
        $user && $password && $password_confirm == "" || " ") {
        return false;
    } else {
        return true;
    }
}