In the previous lesson you saw how to get text
from a textbox when a Submit button on a form was clicked. However, when you
first load the page the text still displays.
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:
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']
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 lesson to the following and try it
out:
isset( )
$_POST['Submit1']
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!
0 comments:
Post a Comment