Passing variables from a PHP Web form to a Web page

When you have the PHP module running on Apache, one of the things you can have PHP do is pass input from the page viewer, as taken from an online form, to use as part of another Web page.

First you create two pages. One will be, for instance, a Web form asking the viewer to type in his/her first and last name...

Embed the following within the body of a new HTML page, called interact.html :
<FORM ACTION="hello.php" METHOD=GET>
First Name: <INPUT TYPE=TEXT NAME="firstname">
Last Name: <INPUT TYPE=TEXT NAME="lastname">
<INPUT TYPE=SUBMIT VALUE="GO">
</FORM>
Then create a second Web page, called hello.php, and insert the following PHP script:
<?php
$firstname = $_GET["firstname"];
$lastname = $_GET["lastname"];
echo( "Hello, $firstname $lastname!" );
?>
In the first page, the Web form calls for the user to enter a first name and a last name, and assigns variables to each. Whne the submit button is clicked, those variables are passed to the the second page hello.php, which is rendered by the server software as a page saying, in this instance:
"Hello Bob Smith!"
PHP offers the server instruction on how to execute tasks, those tasks that result on the out of "echo" get printed to the browser page being created. In this case, the PHP script instructs the server where to insert the variable names ("$firstname" "$lastname") in a string of text.

One bit the original tutorial failed to point out is that, with PHP, you must fetch the variables from memory, which requires an additional step. This is the reason for the "$firstname = $_GET["firstname"];" line....

From the tutorial Building a Database-Driven Web Site Using PHP and MySQL: User Interaction and Forms. And some troubleshooting help from here.

Back