Others have told you how to solve the problem. I will tell you what the problem is.
Problems
You need to know following things:
PHP's boolean to string implicit conversion
When implicitly converting a boolean to a string, PHP acts a bit weird.
$testVar = false;
echo (string)$testVar; //will output a empty string (as that evaluates to false)
$testVar = true;
echo (string)$testVar; //will output 1 (as that evaluates to true)
How isset()
works
According to the PHP Manual,
Returns TRUE
if [variable supplied as argument] exists and has value other than NULL, FALSE otherwise.
What happens when you try to access a $_POST parameter
As you very well know, $_POST
parameters are available to a PHP script when,
- There is an HTML form, of which
action
attribute points to the PHP script
- User submits the form, with or without data
If the name
attribute of a field in the form was "username"
, you can access this information from the PHP script after the submission of the form like this:
$_POST["username"]
But if the PHP script that processes the $_POST
parameters are in the same file as the HTML form, no $_POST
parameters will be available to the script when it is initially accessed.
And if you tried to access $_POST
parameters when there are none, the result is Undefined index
.
What's happening here?
With the understanding of the above three things, we can deduce what's happening in your case.
When your file is loaded on the first time to the browser, PHP interpreter has to interpret it first. But on this first time, no $_POST
variables are present. So when you try to access $_POST
parameters, it will result in an Undefined index
error.
When you wrap the $_POST["..."]
expressions in an isset()
, isset()
will return FALSE
, because the parameters are simply not there. Since FALSE
is converted to empty string (""
), your echo
statement produces nothing visible.
When you submit the form, the isset()
calls will return TRUE
, because the $_POST
parameters are present this time. And as described above, TRUE
becomes "1"
when converted to strings. Hence you get the output 1
.
Solution
You must always check before you access $_POST
parameters.
$username = "";
if (isset($_POST["username"])) {
$username = $_POST["username"];
}
Or shorthand:
$username = isset($_POST["username"]) ? $_POST["username"] : "";
<form action="" method="post">
will post back to the current URL, which is useful if you decide to do "pretty URLs" later on. It also preserves all query string parameters. – Niet the Dark Absol 8 hours ago