I am self studying newbie to PHP. I would like to run a small PHP script only if the submit button is clicked. Unfortunately the function isset()
that (according to my tutorial lesson) performs this submit button check -does not seem to be working !
When I refresh the page in the browser, part of the PHP script: print("You're not a member of this site");
is still getting executed even though I have not yet pressed the submit button! Why?
and the code:
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="basicForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" NAME="username">
<p>
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>
</body>
</html>
instead of isset()
USE
!empty($_POST)
If you are using browser's refresh or the F5
key you need to redirect immediately after submission and it wont surpass isset on refreshing.
Like after mysql_query
function which you have written for INSERT record on form submission you need to write a
header('Location:yourpage.php')
And it will prevent this behaviour.
Im also new to php, will just share my experience.. I have 2 visions of this.. 1st is if you have many forms, you need to add the form="form1" attrtibute insde inputs and buttons to have a single form for the $_POST.
second thought is..
without ajax, the $_POST method sends the data on click but the request from the server comes after refresh only. Meaning the data shown from the post is 1 refresh behind.
You can add a hidden radio or check button with some "check value" like "1".. untill this button receives a value, you can then compare the value, if its true, then you show one message, if not, then another.
But you need a default value, either an empty one or it will always start from "you are not a member" untill the checkbox changes value.
<?php
$username = "";
$username = (isset($_POST['Submit1']) ? $_POST['Submit1'] : "");
?>
<Form name ="form1" Method ="POST" Action ="basicForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" NAME="username">
<INPUT hidden TYPE = "checkbox" NAME="check_trigger"
<?php if(!is_empty($username)){ echo "checked";}; ?> >
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>
so when the username is entered, the checkbox gets autochecked, and you can echo the greeting message even if the name is changed... am i out of topic..
or you can put your name as default inside isset
$username = (isset($_POST['Submit1']) ? $_POST['Submit1'] : "letmein");
and have
<INPUT TYPE = "TEXT"
VALUE =<?php"echo htmlspecialchars($username);?>" NAME="username">
but you need some validation and security for it.