Home > Software engineering >  How do i make the variable work using the input field?
How do i make the variable work using the input field?

Time:01-14

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h3>MAD LIBS</h3>
    <?php
      if (isset($_POST['submit'])) {
        $color = $_POST['color'];
        $pluralNoun = $_POST['pluralNoun'];
        $celebrity = $_POST['celebrity'];
      }

      echo "Roses are " . $color;
      echo $pluralNoun . " are Blue";
      echo "I love " . $celebrity;
     ?>

    <form action="site.php" method="post">
      Color: <input type="text" name="color"> <br>
      Plural Noun: <input type="text" name="pluralNoun"> <br>
      Celebrity: <input type="text" name="celebrity"> <br>
      <input type="submit" name="submit"> <br>
    </form>



    <!-- <?php
      if (isset($_POST['color']) && isset($_POST['pluralNoun']) && isset($_POST['celebrity'])) :
        echo "Roses are " . $_POST['color'] . "<br>";
        echo $_POST['pluralNoun'] . " are Blue <br>";
        echo "I love " . $_POST['celebrity'];
      endif;
     ?> -->

  </body>
</html>

Hey guys, I'm completly new to PHP. Can you guys help me how to get this code working? The bottom php code that i commented out is working. But I wanted to use the first php code so i can call ($_POST['']) using variables. But in the website it shows:

Warning: Undefined variable $color in C:\xampp\htdocs\webProgramming\site.php on line 16 Roses are Warning: Undefined variable $pluralNoun in C:\xampp\htdocs\webProgramming\site.php on line 17 are Blue Warning: Undefined variable $celebrity in C:\xampp\htdocs\webProgramming\site.php on line 18 I love

I'm sorry for my bad english, it's not my first langauge. I hope you understand what my questions mean.

CodePudding user response:

For top part of the code you have 2 solutions

  1. Put all in if statement

     if (isset($_POST['submit'])) {
         $color = $_POST['color'];
         $pluralNoun = $_POST['pluralNoun'];
         $celebrity = $_POST['celebrity'];
    
         echo "Roses are " . $color ."<br>";
         echo $pluralNoun . " are Blue <br>";
         echo "I love " . $celebrity ."<br>";
     }
    
  2. Or you can use ternary

    if (isset($_POST['submit'])) {
        $color = $_POST['color'];
        $pluralNoun = $_POST['pluralNoun'];
        $celebrity = $_POST['celebrity'];
    }
    
    echo "Roses are " . ($color ?? "[valu not set]") ."<br>";
    echo ($pluralNoun ?? "[valu not set]") . " are Blue" ."<br>";
    echo "I love " . ($celebrity ?? "[valu not set]") ."<br>";
    
  •  Tags:  
  • Related