0

I have a variable pulled from a WordPress meta array - $vCode.

This variable is a 5 digit number.

On the page front-end I have an HTML form requesting a code to be entered and a submit button.

Upon submit I want the entered code to be checked against $vCode and display either "success" or "fail" if it matches or not.

  1. Should I be using an HTML form here or PHP?
  2. What is the best way to run the check without leaving the page?

This is what I have so far:

$vCode = 11111; $message = ""; if(!isset($_POST['submitbutton'])){ $message = "not submitted"; } elseif ((isset($_POST['submitbutton'])) && ($input = $vCode)) {//check if form was submitted $input = $_POST['vCode']; //get input text $message = "Success! You entered: ".$input; } elseif ((isset($_POST['submitbutton'])) && ($input != $vCode)) { $input = $_POST['vCode']; $message = "OOps"; } ?> <form action="" method="post"> <?php echo $message; ?> Validation Code:<br> <input type="number" name="vCode" value=""><br> <input type="submit" name="submitbutton" value="Submit"> </form> 

This is always showing that I entered the correct number?

Thanks as always.

    1 Answer 1

    1

    Your problem is this bit:

    $input = $vCode 

    That is not comparing the variables. It's assigning the value of $vCode to $input. If you want to compare the two values, you need to use == or ===.

    $input == $vCode 

    It still wouldn't work though, because you haven't actually defined $input. You're only defining it after the comparison, which isn't much use.

    So your logic needs to look like this:

    $vCode = 11111; $message = ''; if( ! isset( $_POST['submitbutton'] ) ) { $message = 'not submitted'; } else { $input = $_POST['vCode']; if ( $input == $vCode ) { $message = 'Success! You entered: ' . $input; } elseif ( $input != $vCode ) { $message = 'OOps'; } } 

    Note that:

    • We're assigning $_POST['vCode'] to $input before checking it.
    • We're not bothering to check if $_POST['submitbutton'] is set, because the only reason that code would be running is if it was, because of the first condition.
    • We're using == to compare the value. We're using == and not ===, because $vCode is an integer, while $_POST['vCode'] will be a string. If you're actually getting $vCode from post meta, then it will also be a string, in which case you can use ===.

    Regarding that last point, the best solution would be to convert them both to integers and use a strict comparison:

    if ( (int) $input === (int) $vCode ) { 
    1
    • Thank you for explaining, it now works as intended.
      – Shaun21uk
      CommentedMay 31, 2019 at 6:32

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.