Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

php - Trying to select and print the submitted answer in my dropdown

I have this small Capital quiz i have to make for a school project, first, i had to import all options using a php array, which i did as you can see in the code. i've made sure you could choose every capital using a foreach loop in the tag. The problem is, i dont know how to save the submitted answer. and print it under the button after it has been submitted. If you have an idea, help would be appreciated. Sorry for any grammar mistakes. English isn't my first language.

<html>
  <head>
  </head>
    <body>
      <?php $capital = array(
      "Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels", "Denmark"=>"Copenhagen",
      "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava", "Slovenia"=>"Ljubljana",
      "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin", "Netherlands"=>"Amsterdam",
      "Portugal"=>"Lisbon", "Spain"=>"Madrid", "Sweden"=>"Stockholm", "United Kingdom"=>"London",
      "Cyprus"=>"Nicosia", "Lithuania"=>"Vilnius", "Czech Republic"=>"Prague", "Estonia"=>"Tallin",
      "Hungary"=>"Budapest", "Latvia"=>"Riga", "Malta"=>"Valetta", "Austria" => "Vienna",
      "Poland"=>"Warsaw") ;
      $l = array_rand($capital);
      $h = $capital[$l]; 
      echo "What is the capital of ".$l."?";
      ?>
      <br><br>
      <form method="POST">
        <select name="cap">
          <?php
          foreach ($capital as $country => $city) {
            ?>
            <option value="<?php echo $city ?>" ><?php echo $city ?></option>
            <?php } ?>
        </select>
      <br><br>
      <input type="submit" value="Check Answer!">
      <br><br>
    </form>
    <?php
    if(isset($_POST['submit'])){
      $getCapital=$_POST[$capital];
      echo "Your answer was ".$getCapital;
    }
?>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because you gave the field on the form the name cap in this line

<select name="cap">

To access the value the user selected in that select dropdown is

if(isset($_POST['submit'])){
    echo "Your answer was ".$_POST['cap'];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...