I have a page where I want to pull up information based on zipcodes. When a person goes to the page on the first visit the zipcode $variable is null because they haven’t filled out the form and the page gives me an “undefined variable” error. So, I wrote this little if/else statement to fix it but it isn’t working like I had hoped.
(form goes here to input zipcode using method = “POST”)
<?php
if ($zipcode = 'null' ) {
( $zipcode = '83777' );
} else {
($zipcode = $_POST['zipcode'] );
}
The variable appears in my 'echo' statement as 83777 on the first visit but when the form is filled out the new zipcode isn't passed along. For the record everything works without the if/else statement except for the initial "undefined variable" error.
That in itself is fine, it’s just that you weren’t using isset() to check if the variable exists, you were comparing it to ‘null’, and you were comparing the variable you haven’t created yet instead of the $_POST variable. There’s a difference between a variable not existing and one that is equal to ‘null’. Another way would have been to just change your first line to
if (!isset($_POST['zipcode'])) {
for the same effect. So if the $_POST variable does not exist, set $zipcode to a fixed value, otherwise set it to the value of the $_POST variable.
However the error-reporting lines in the post from @John_Betong are useful to set during the development stage.
Practice frequently and learn to love the Online Manual which is one of the best manuals I have encountered and also has numerous examples.
PHP7 has some very nice features and is provided by most hosts.
I forgot to mention that the following should be set differently if the script is used online to prevent errors and warnings being displayed on the screen.
Try this:
<?php
define('LOCALHOST', 'localhost' === $_SERVER[['SERVER_NAME');
// SET ONLINE DEFAULTS
error_reporting(-1);
ini_set('display_errors', '0'); // should save errors and warnings to a log file
if( LOCALHOST ):
ini_set('display_errors', '1');
endf;
Thanks for the information. It worked well. I did have a few more problems with the form but unrelated to your fix. I have been able to figure them out with a lot of searching and trial and error.
I’ve started using the online manual as you recommend. Another great resource is the w3schools website. Short and sweet.