簡體   English   中英

HTML 形式的正確 PHP 輸入

[英]Proper PHP input for HTML form

目前我的 PHP 文件出現“未知索引”錯誤。

我在 HTML 上創建了一個表單,要求用戶在文本框中輸入信息。 這是一個基本的計算,如 5X3,因此用戶必須輸入“15”。 然后我需要使用 PHP 以及 if-else 語句來確定用戶是否正確輸入了正確的數字。 但我相信我沒有正確設置我的 PHP 文件。 這是我第一次使用 PHP,所以我不完全確定可以使用哪些其他替代方案。 我幾乎只是根據我們的講義中的示例構建了我的 PHP 文件。 我是否正確設置了所有內容?

//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.";
  }

做得好,沒錯://如果用戶輸入正確答案實際結果:

注意:未定義索引:第 6 行 /Applications/XAMPP/xamppfiles/htdocs/CIT273/timetable.php 中的 Q1

您首先需要將您的輸入包裝在帶有 post 操作的表單標簽中

<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.";
        }
?>

試試這個。

<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.";
        }
    }
?>

你可以通過兩種方式解決這個問題

正如@Robin Singh 指出的那樣//對應 label 的 PHP 代碼

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

或者

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

這樣,當用戶不輸入任何內容時,您將在 $Q3 中擁有 null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM