PHP fetch the value from the select html page-ThrowExceptions

Exception or error:

i have below html code

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" class="contact">
            <label id="name">
                <h4>name*</h4>
                <input type="text" name="name" placeholder="full name" autofocus/>
            </label>
            <label id="city">
                <h4>city</h4>
            <select name="city">
            <option value="Afghanistan">Afghanistan</option>
            <option value="Albania">Albania</option>
                        </select>
            </label>

PHP code

if($_POST["name"] == null)
{
    echo "<p class='wrong'><strong>wrong: </strong> name is empty</p>";
}
if($_POST["city"] == null)
{
    echo "<p class='wrong'><strong>wrong: </strong> city is empty</p>";
}

this to check the null value and always gives the city is empty that means no value selected

How to solve:

Cannot comment yet.

Maybe try and close the label before the select.

 <label id="city">
   <h4>city</h4>
 </label>         
 <select name="city">
   <option value="Afghanistan">Afghanistan</option>
   <option value="Albania">Albania</option>
 </select>

and maybe do

<?php echo "<pre>".print_r($_POST,true)."<pre>";

to see what values are set.

And as others have suggested check of the value is empty()

if(!isset($_POST['city'])||empty($_POST['city']))

This returns true if city is empty, has no value or true if it doesn’t exist.

Hope this helps!

Edit 1:

Also since the php code is probably on the same page, could just omit the action attribute.

<form method="POST" class="contact">
 <label for="city">
   <h4>city</h4>
 </label>         
 <select id="city" name="city">
   <option value="Afghanistan">Afghanistan</option>
   <option value="Albania">Albania</option>
 </select>
</form>

also use the for attribute with the ID of the input field you want it to represent

Leave a Reply

Your email address will not be published. Required fields are marked *