PHP Tutorial - PHP Form TextField






A text input field allows the user to enter a single line of text.

Value attribute

You can optionally prefill the field with an initial value using the value attribute . To leave it blank, specify an empty string for the value attribute, or leave the attribute out altogether.

<label for="textField">A text input field</label> 
<input type="text" name="textField" id="textField" value="" /> 

Example 1

The following code is for index.htm file and it has a text field and submit button.

<html>
<body>
   <form action="index.php" method="get">
      <input type="text" name="user" />
      <input type="submit" value="hit it!" />
    </form>
</body>
</html>

Name the following script as index.php and put it into the same folder as above index.htm file. It accepts the value from the text field by using field name user.


<?php
  print "Welcome <b>" . $_GET ['user'] . "</b><br/>";
?>




Example 2

A PHP Number Guessing Script


<?php// ww  w .jav a  2s  .  c o m
$num_to_guess = 42;
$message = "";
if ( ! isset( $_POST['guess'] ) ) {
   $message = "Welcome!";
} else if ( $_POST['guess'] > $num_to_guess ) {
   $message = $_POST['guess']." is too big!";
} else if ( $_POST['guess'] < $num_to_guess ) {
   $message = $_POST['guess']." is too small!";
} else { 
   $message = "Well done!";
}
?>
<html>
<body>
  <h1> 
     <?php print $message ?> 
  </h1>
  <form method="post" action="<?php print $_SERVER['PHP_SELF']?>">
  <p>
     Type your guess here: 
     <input type="text" name="guess" />
     <input type="submit" value="submit" />
  </p>
  </form>
</body>
</html>