If you know a little HTML, then you know that the FORM tags can be used to interact with your users. Things that can be added to a form are the likes of text boxes, radio buttons, check boxes, drop down lists, text areas, and submit buttons. A basic HTML form with a textbox and a Submit button looks like this:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "">
<INPUT TYPE = "TEXT" VALUE ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>
</html>
We won't explain what all the HTML elements do, as this is a book on PHP. Some familiarity with the above is assumed. But we'll discuss the METHOD, ACTION and SUBMIT attributes in the form above, because they are important.
So, create the form above. Save your work as basicForm.php. (This name will be VERY important!) Start your server, and make sure the form loads ok in your browser. You should be able to see a text box and a Submit button. Here's what it should look like:
If a user comes to your site and has to login, for example, then you'll need to get the details from textboxes. Once you get the text that the user entered, you then test it against a list of your users (this list is usually stored on a database, which we'll see how to code for in a later section). First, you need to know about the HTML attributes METHOD, ACTION and SUBMIT.
you'll notice a METHOD attribute:
<FORM NAME ="form1" METHOD =" " ACTION = "">
The Method attribute is used to tell the browser how the form information should be sent. The two most popular methods you can use are GET and POST. But our METHOD is blank. So change it to this:
<FORM NAME ="form1" METHOD ="GET" ACTION = "">
To see what effect using GET has, save your work again and then click the Submit button on your form. You should see this:
The thing to notice here is the address bar. After basicForm.php, we have the following:
?Submit1=Login
This is a consequence of using the GET method. The data from the form ends up in the address bar. You'll see a question mark, followed by form data. In the image above, Submit1 was the NAME of the button, and Login was the VALUE of the button (the text on the button). This is what is being returned by the GET method. You use the GET method when the data you want returned is not crucial information that needs protecting.
You can also use POST as the Method, instead of GET.
you saw what happened in the browser's address bar when you used the GET method for Form data. The alternative to GET is to use POST. Change the first line of your FORM to this:
Close your browser down, and open it back up. Load your basicForm.php page again, and then click the button. Your address bar will then look like this:
<FORM NAME ="form1" METHOD ="POST" ACTION = "">
The ?Submit1=Login part from the previous section is now gone! That is because we used POST as the method. Using POST means that the form data won't get appended to the address in the address bar for all to see. We'll use both POST and GET throughout the book. But it depends on the project: if the data is not sensitive then use GET, otherwise use POST.
In PHP, a popular technique is to send the script to the same page that the form is on – send it to itself, in other words. We'll use that technique first, but you'll see both techniques in action.
Locate the following, and amend the ACTION line to this:
<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">
So we're going to be sending the form data to exactly the same page as the one we have loaded – to itself. We'll put some PHP on the page to handle the form data. But for now, save your work again and then click your submit button. You won't see anything different, but you shouldn't see any error message either!
The HTML Submit button is used to submit form data to the script mentioned in the ACTION attribute. Here's ours:
<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">
So the page mentioned in the ACTION attribute is basicForm.php. To Submit this script, you just need a HTML Submit button:
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
You don't need to do anything special with a Submit button – all the submitting is done behind your back. As long as SUBMIT has an ACTION set, then your data will get sent somewhere. But the NAME attribute of the Submit buttons comes in very handy. You can use this Name to test if the form was really submitted, or if the user just clicked the refresh button. This is important when the PHP script is on the same page as the HTML form. Our Submit button is called "Submit1", but you can call it almost anything you like.
Now that you know about METHOD, ACTION, and SUBMIT, we can move on to processing the data that the user entered. First, how to get values from our text box.
We're going to use these to process text that a user has entered into a text box. The METHOD attribute tells you how form data is being sent, and the ACTION attribute tells you where it is being sent.
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME yet, so change your HTML to this:
The NAME of our textbox is username. It's this name that we will be using in a PHP script.
To return data from a HTML form element, you use the following strange syntax:
Before we explain all the syntax, add the following PHP script to the HTML code you have so far. Make sure to add it the HEAD section of your HTML (the part to add is in bold):
Save your work again, and click the submit button to run your script. (Don't worry if you see an error message about "Undefined index". Click the button anyway.) You should see this appear above your text box:
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME yet, so change your HTML to this:
<INPUT TYPE = "Text" VALUE ="username" NAME = "username">
To return data from a HTML form element, you use the following strange syntax:
$_POST['formElement_name'];
You can assign this to a variable:
$Your_Variable = $_POST['formElement_name'];
<html>
<head>
<title>A BASIC HTML FORM</title>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
$username = $_POST['username'];
print ($username);
print ($username);
?>
</head>
Delete the text "username" from the textbox, and click the button again. Your new text should appear above the textbox. The text box itself, however, will still have "username" in it. This is because the text box is getting reset when the data is returned to the browser. The Value attribute of the text box is what is being displayed.
So how does it work?
The $_POST[ ] is an inbuilt function you can use to get POST data from a form. If you had METHOD = "GET" on your form, then you'd used this instead:
$username = $_GET['username'];
So you begin with a dollar sign ($) and an underscore character ( _ ). Next comes the METHOD you want to use, POST or GET. You need to type a pair of square brackets next. In between the square brackets, you type the NAME of your HTML form element – username, in our case.
$_POST['username'];
Of course, you need the semi-colon to complete the line.
Whatever the VALUE was for your HTML element is what gets returned. You can then assign this to a variable:
$username = $_POST['username'];
So PHP will look for a HTML form element with the NAME username. It then looks at the VALUE attribute for this form element. It returns this value for you to use and manipulate.
At the moment, all we're doing is returning what the user entered and printing it to the page. But we can use a bit of Conditional Logic to test what is inside of the variable. As an example, change your PHP to this:
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
else {
print ("You're not a member of this site");
}
We're now checking to see if the user entered the text "letmein". If so, the username is correct; if not, print another message.
Try it out an see what happens. When you first load the page, before you even click the button, you might see the text "You're not a member of this site" displayed above the textbox. That's because we haven't checked to see if the Submit button on the form was clicked.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if ( isset( $_POST['Submit1'] ) ) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit1']
isset( )
$_POST['Submit1']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
else {
print ("You're not a member of this site");
}
}
Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!
You don't have to submit your form data to the same PHP page, as we've been doing. You can send it to an entirely different PHP page. To see how it works, try this:
Create the following page, and call it basicForm2.php. This is your HTML. Notice the ACTION attribue.
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="submitForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" Name ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>
</html>
Now create the following page, and call it submitForm.php:
<?PHP
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
else {
print ("You're not a member of this site");
}
?>
In the PHP script above, notice how there's no HTML tags. And we've left out the code that checks if the Submit button was clicked. That's because there's no PHP left in the first page. The code only gets executed IF the Submit is clicked.
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But there is a problem with it, which you will have noticed: the script gets executed on a new page. That means your form will disappear!
If you look at the VALUE attribute of the text box in the HTML from the above script, you'll see that it's set to "username". Because the form gets posted back to itself, this value will keep re-appearing in the textbox when the page is submitted. Worse, if you've left the Value attributes empty then everything the user entered will disappear. This can be very annoying, if you're asking the user to try again. Better is to POST back the values that the user entered.
To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
VALUE="<?PHP print $username ; ?>"
In other words, the VALUE attribute is now a PHP line of code. The line of code is just this:
<?PHP
print $username ;
?>
It's a bit hard to read, because it's all on one line.
You also need to amend your PHP code in the HEAD section to include an else statement:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
else {
print ("You're not a member of this site");
}
}
else {
else {
$username ="";
}
In the else statement at the end, we're just setting the value of the variable called $username for when the button is NOT clicked, i.e. when the page is refreshed.
However, there are some security issues associated with textboxes (and other form elements). So we'll see a more secure way to handle these in a later section.
But our new line of HTML for our textbox reads like this:
<INPUT TYPE = 'TEXT' Name ='username' VALUE="<?PHP print $username ; ?>">
In other words, we're now printing out the VALUE attribute with PHP code.
A Radio Button is a way to restrict users to having only one choice. Examples are : Male/Female, Yes/No, or answers to surveys and quizzes.
Here's a simple from with just two radio buttons and a Submit button:
Here's a simple from with just two radio buttons and a Submit button:
Make sure you save your work as radioButton.php, as that's where we're posting the Form – to itself.
To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML form elements. In the HTML above, the NAME of the Radio buttons is the same – "gender". The first Radio Button has a value of "male" and the second Radio Button has a value of female. When you're writing your PHP code, it's these values that are returned. Here's some PHP code. Add it to the HEAD section of your HTML:
<?PHP
$selected_radio = $_POST['gender'];
print $selected_radio;
print $selected_radio;
?>
This is more or less the same code as we used for the text box! The only thing that's changed (apart from the variable name) is the NAME of the HTML form element we want to access – "gender". The last line just prints the value to the page. Again, though, we can add code to detect if the user clicked the Submit button:
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
print $selected_radio;
}
Again, this is the same code you saw earlier – just access the form element called 'Submit1' and see if it is set. The code only executes if it is.
Try out the code. Select a radio button and click Submit button. The choice you made is printed to the page - either "male" or "female". What you will notice, however, when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. Again, PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little more complex than for text boxes
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
<?PHP
$male_status = 'unchecked';
$female_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
<FORM name ="form1" method ="post" action ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'
<?PHP print $male_status; ?>
>Male
<?PHP print $male_status; ?>
>Male
<Input type = 'Radio' Name ='gender' value= 'female'
<?PHP print $female_status; ?>
>Female
<?PHP print $female_status; ?>
>Female
<P>
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>
Did we say a little more complex? OK, it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first:
<?PHP print $female_status; ?>
This is just a print statement. What is printed out is the value inside of the variable. What is inside of the variable will be either the word "checked" or the word "unchecked". Which it is depends on the logic from our long PHP at the top of the page. Let's break that down.
First we have two variables at the top of the code:
$male_status = 'unchecked';
$female_status = 'unchecked';
$female_status = 'unchecked';
These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit button being clicked.
Next we have our check to see if Submit is clicked:
if (isset($_POST['Submit1'])) {
}
Exactly the same as before. As is the next line that puts which radio button was selected into the variable:
$selected_radio = $_POST['gender'];
We then need some conditional logic. We need to set a variable to "checked", so we have an if, else … if construction:
if ($selected_radio == 'male') {
}
else if ($selected_radio == 'female') {
else if ($selected_radio == 'female') {
}
All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one thing; if it's 'female', do another. But look at what we're doing:
if ($selected_radio == 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'.
So the code works because of the values inside of two variables: $male_status and $female_status.
Here's a page that asks users to choose which course books they want to order:
As you can see, five items can be selected. Only three are chosen at the moment. When the button is clicked you, as the programmer, want to do at least two things: record which checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of errors.
You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding. The same is true for checkboxes.
Note one thing about the HTML checkbox elements: they all have different NAME values (ch1, ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME. That's because only one option can be selected with Radio Buttons. Because the user can select more than one option with Checkboxes, it makes sense to give them different NAME values, and treat them as separate entities (but some advocate treating them just like Radio Buttons).
In your PHP code, the technique is to check whether each checkbox element has been checked or not. It's more or less the same as for the radio Buttons. First we set up five variable and set them all the unchecked, just like we did before:
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
The next thing is the same as well: check to see if the Submit button was clicked:
if (isset($_POST['Submit1'])) {
}
Inside of this code, however, we have another isset( ) function:
if ( isset($_POST['ch1']) ) {
}
This time, we're checking to see if a checkbox was set. We need to do this because of a peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is returned! If you try the code without checking if the checkboxes are set, then you'll have to deal with a lot of "Undefined" errors.
If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true. If the isset( ) function is true, then our code inside of the if statement gets executed:
if ($ch1 == 'net') {
$ch1 = 'checked';
}
This is yet another If Statement! But we're just checking the value of a variable. We need to know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net' then execute some code.
The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The rest of the if statements are the same – one for each checkbox on the form.
The last thing we need to do is to print the value of the variable to the HTML form:
<Input type = 'Checkbox' Name ='ch1' value ="net"
<?PHP print $ch1; ?>
>Visual Basic .NET
<?PHP print $ch1; ?>
>Visual Basic .NET
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
<?PHP print $ch1; ?>
So we're just printing what is inside of the variable called $ch1. This will either be "unchecked" or "checked",
There are other solution for checkboxes, but none seem simple! The point here, though, is that to get the job done we used Conditional Logic.
No comments:
Post a Comment