Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - PHP form using Post. Error: Undefined array key. However it works when I use get. (w3schools example)

I am trying to make a form on my website where users can submit their name and their score will get saved to a list of highscores. (its a quiz game.)

I tried learning to use forms using w3schools. I used this example: https://www.w3schools.com/php/php_forms.asp

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

with welcome.php looking like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html> 

I literally copy and pasted this example and tried running it and i get this error message:

WelcomeWarning: Undefined array key "name" in [filelocation] on line 4

Your email address is:Warning: Undefined array key "email" in [filelocation] on line 5

However when I replaced all the "post" with "get" it worked. Why? What do I need to do to get it to work with post?

EDIT: Also I left the "post" in the html but i replaced the POST in the welcome.php with REQUEST. It now works, however I think its somehow using GET instead of POSTs because i can see the input in the URL. I definitely need to avoid this. Maybe this helps

Thank you!

question from:https://stackoverflow.com/questions/65541232/php-form-using-post-error-undefined-array-key-however-it-works-when-i-use-get

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

1 Answer

0 votes
by (71.8m points)

you might running directly welcome.php page.

Replace your welcome.php with

<html>
<body>
    <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { ?>
    Welcome <?php echo $_POST["name"]; ?><br>
    Your email address is: <?php echo $_POST["email"]; ?>
    <?php }
          else{ ?>
     <script> location.replace("yourHtmlFileName.html") </script>
     <?php     } ?>
</body>
</html> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...