GraysonG
GraysonG

Reputation: 11

Proper PHP input for HTML form

Currently getting an 'Unidentified Index' error for my PHP file.

I created a form on an HTML that requires users to enter info into a textbox. It's a basic calculation, like 5X3, so the user must enter '15'. I then need to use PHP as well as an if-else statement to determine if the user correctly entered the right number. But I believe that I have not properly set up my PHP file. This is my first time using PHP, so I'm not entirely sure what other alternatives to using. I have pretty much just structured my PHP file off examples from our lecture notes. Have I properly set everything up?

//HTML form code
<label for="Question 3">Question Three: <strong>2 X 9</strong></label><br>
<input type="text" id="Q3" name="Q3" placeholder="Type Answer Here"><br>

//PHP code for corresponding label
$Q3 = $_POST['Q3'];

//if statement regarding a particular question
if ($Q3 == "18")
  {
    echo "Well done, that's Correct!";
  }
  else
  {
    echo "Sorry, that's incorrect.";
  }

Well done, that's correct! //if user inputs correct answer actual results:

Notice: Undefined index: Q1 in /Applications/XAMPP/xamppfiles/htdocs/CIT273/timetable.php on line 6

Upvotes: 1

Views: 102

Answers (3)

Shubham Narvekar
Shubham Narvekar

Reputation: 77

You first need to wrap ur input in a form tag with a post action

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  <label for="Question 3">Question Three: <strong>2 X 9</strong></label>
  <input type="text" id="Q3" name="Q3" placeholder="Type Answer Here">
  <input type="submit" name="submit" value="Submit">  
</form>

<?php
        //if statement regarding a particular question
        if ($_POST['Q3'] == "18") {
            echo "That's Correct!";
        } else {
            echo "That's incorrect.";
        }
?>

Upvotes: 3

Viszman
Viszman

Reputation: 1398

you can resolve that in 2 ways

as @Robin Singh pointed //PHP code for corresponding label

if(!isset($_POST['Q3'])) {
    $Q3 = null;
}

OR

$Q3 = $_POST['Q3'] ?? null

that way you will have null in $Q3 when user don't input anything

Upvotes: 0

Krupal Panchal
Krupal Panchal

Reputation: 1545

Try This one.

<form method="post">
    <label for="Question 3">Question Three: <strong>2 X 9</strong></label><br>
    <input type="text" id="Q3" name="Q3" placeholder="Type Answer Here"><br>
</form>

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $Q3 = $_POST['Q3'];

        //if statement regarding a particular question
        if ($Q3 == "18") {
            echo "Well done, that's Correct!";
        } else {
            echo "Sorry, that's incorrect.";
        }
    }
?>

Upvotes: 0

Related Questions