PHP: Forms

In this tutorial I will explain:
•PHP Form processing…
•How to save and display someones name.

I assume you know:
•PHP Variables and Basic Functions…
•XHTML Forms.

Forms are the the first step to jazz up your website with PHP; They are a very simple way to include user-interactivity. To start, look at an XHTML Form [The part the user sees]:

  1. <form method="POST" action="showName.php">
  2. First Name:<input name="firstName" type="text" /><br>
  3. Last Name:<input name="lastName" type="text" /><br>
  4. <input value="Go!" name="submit" type="submit" />
  5. </form>

There are multiple “things” in that source code that you may have not realized did something. First off, method is how the data is passed to the action, or PHP Page. Post sends the data invisible, and Get sends the data in the URL. The good thing about Get is that you can still bookmark the website, but with Post you trade in speed and friendliness for secrecy. The second thing is the name attributes of the input items. These are how you get data from the input items in PHP. Hopefully this will all come clear in this example:

  1. <?php //showName.php
  2. //Create the variables
  3. $fName;
  4. $lName;
  5.  
  6. //Set the values by retrieving them from the form
  7. //Notice inside the quotations are the input item names…
  8. //$_POST[’Forms Item Name’];
  9. $fName=$_POST[‘firstName’];
  10. $lName=$_POST[‘lastName’];
  11.  
  12. //Display the Variables using echo()
  13. echo("Hello $fName $lName");
  14. ?>

I’m not going to explain much, since I believe it’s best to learn by example, and you should try different variations for your self. Test your knowledge, find the limits of this tutorial. So instead of going through this code, (Make use the the comments in the source code) I am going to give you a list of things to try out…

•Use GET instead of POST for the Form Method…
•Adding input fields and incorporating those into the PHP file…
•Use an If conditional to see if a given password is correct, and tell the user if it is valid or not.

NOTE:

  1. <?php
  2. //For POST
  3. $_POST[‘ItemName’];
  4.  
  5. //For GET
  6. $_GET[‘ItemName’];
  7. ?>

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: