简体   繁体   中英

How to set a default value for an HTML form input?

So I have made a small form in HTML, which allows users to enter their name, and then it is displayed on the site. This works fine apart from the first time you visit the page since the input field doesn't hold a value yet, and so it displays an error message when trying to render the PHP. I was wondering whether there is any way to set a default value for the input field so I don't get this error.

Here is my code:

<html>
<head>
    <title>My PHP Site</title>
</head>
<body>
    <h1>My PHP Site</h1>
    <form action="dynamictest.php" method="post">
        <input type="text" name="username" placeholder="Username">  
        <input type="submit"><br>
    </form>
    <?php
      if ($_POST['username'] === '') {
          echo "<p>Welcome, stranger.</p>";
      } else {
          echo "<p>Welcome, {$_POST['username']}.</p>";
      }
    ?>
</body>
</html>

In your PHP code, you should check whether the request is a POST before trying to handle POST elements:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ($_POST['username'] === '') {
    echo "<p>Welcome, stranger.</p>";
  } else {
    echo "<p>Welcome, {$_POST['username']}.</p>";
  }
}
?>

This will not run your existing code if the page is not a POST , and therefore the situation causing the error will not occur.

I can imagin you're getting an "Undefined index" error from php. In this case it's because you're trying to access a field which does not exist when you're loading the page with a GET request.

To circumvent this you can check if this key exist.

if (array_key_exists('username', $_POST) && $_POST['username'] === '') {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM