Jump to content

How to code a Drop-down list in PHP


Patwan

Recommended Posts

Hi all,
I have a HTML contact form on my website whereby when the user hits submit button I get all other inputs in my email except option from Drop-down list. What could be the problem?

~ Kindly assist

<?php
//initialize variables and set to empty values
$name = $phone = $email = $business = $industry= "";
$nameErr = $phoneErr = $emailErr = $businessErr = $industryErr="";

ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $valid = true;

    //check if name contains letters and white-space
    if (empty($_POST["name"])) {

        $valid = false;

        $nameErr = "Please fill out this field";
        echo 'name is empty<br>';
    } else {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ,.-]*$/", $name)) {

            $valid = false;

            $nameErr = "*Only Letters and white-spaces are allowed*";
        } /* else {
          echo'name is valid<br>';
          } */
    }

    //check if phone contains numbers
    if (empty($_POST["phone"])) {

        $valid = false;

        $phoneErr = "Please fill out this field";
        echo'phone is empty<br>';
    } else {
        $phone = test_input($_POST["phone"]);
        if (!preg_match("/^[0-9 ,+.-]*$/", $phone)) {

            $valid = false;

            $phoneErr = "*Only numbers are allowed*";
        
        }

        /*   else {
          echo'  phone is valid<br>';
          } */
    }

    //check if email is valid
    if (empty($_POST["email"])) {

        $valid = false;

        $emailErr = "Please fill out this field";
        echo'email is empty<br>';
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $valid = false;

            $emailErr = "*Invalid email address*";
           
        }

        /*  else {
          echo'email is valid<br>';
          }
         */
    }
	
	      //check if industry is filled
	 if (empty($_POST["industry"])) {
		 $industryErr = "Please Select an item";
	} else 
	{$industry = test_input($_POST["industry"]);}
	
	
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta name= "robots" content= "noindex, nofollow">
        <meta charset="UTF-8">
        <meta name= "author" content= "Kelly James">
        <link href= "style.css" rel= "stylesheet" type= "text/css">
        <title> Contact form </title>
    </head>

    <body>

        <img src= "images/logo.gif" border= "0" width= "240" height="160">

        <br>
        <div class="form">

            <form method= "post" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >

                <h4 id="h4form"> Please fill the form below to kick start your project. <br> <br> <font color="red"> *required field </font> </h4>

                <br> What is your name? <input type= "text" class= "input" name= "name"  placeholder= "e.g Nelson Mandela" value="<?php echo $name; ?>"  required> <span class= "error"> * <br> <?php echo $nameErr; ?> </span>

                <br> <br>What is your phone number? <input type= "text" class= "input" name= "phone"  value="<?php echo $phone; ?>" placeholder= "e.g 0722222222" required> <span class= "error"> * <br> <?php echo $phoneErr; ?> </span>

                <br> <br> What is your email address? <input type= "email" class= "input" name= "email" placeholder= "will not be published" value="<?php echo $email; ?>" required> <span class= "error"> * <br> <?php echo $emailErr; ?> </span>
				
				<br> <br> What industry is your business? <span class= "error"> * <?php echo $industryErr;?> </span>
                    <select class= "input" name="industry" required>
                     <option value= "" > Select  Industry </option>
                     <option value= "Air_and_Travel" >Air & Travel </option>
                     <option value= "Agriculture">Agriculture</option> 
					 <option value= "Architecture and Structural"> Architecture and Structural </option> 
					 <option value="Attorney & legal"> Attorney & Legal </option> 
					 <option value="Automotive"> Automotive </option>
                     <option value= "Consultation"> Consultation </option>
					 </select> 
					 
				<br> <br> <button class="submit" type= "submit" value= "Submit"> Submit  Form </button>



            </form>
        </div>
    </body>
</html>
Link to comment
Share on other sites

If you mean the drop down list does not reflect the previously selected option, well it wouldn't, all inputs are cleared on reload, you are populating the previous values, with dropdown you would have to loop through each value untill a match is found and add attribute selected, this will mean all the options will need to be reproduced using php with values stored in array, and loop through each using for loop, with if condition to identify match.

Link to comment
Share on other sites

I know you want the user to select one option only, but you can't loop through multi html options and compare with the returned $_POST php value, BUT! You can to php value from php array OR MySQL database records values, looped through depending which you wish to use. Once the looping value match, the looping is stopped, and html attribute 'selected' is added to output of html option elements and values.

  • Like 1
Link to comment
Share on other sites


<!DOCTYPE html>

<!--

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

-->

<html>

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

<?php

$oplist_select = "";

 

If (isset($_POST["industry"]) && !empty($_POST["industry"])) {

 

$oplist_select = $_POST["industry"];

}

 

$oplist = ["Air_and_Travel", "Agriculture", "Architecture and Structural", "Attorney & legal", "Automotive"];

?>

<form method= "post" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >

<select class= "input" name="industry" required>

<option value= "" > Select Industry </option>

<!-- <option value= "Air_and_Travel" >Air & Travel </option>

<option value= "Agriculture">Agriculture</option>

<option value= "Architecture and Structural"> Architecture and Structural </option>

<option value="Attorney & legal"> Attorney & Legal </option>

<option value="Automotive"> Automotive </option>

<option value= "Consultation"> Consultation </option>-->

 

 

<?php

$option_Att_selected = "";

foreach ($oplist as $opt_value) {

$option_Att_selected = "";

if ($opt_value === $oplist_select) {

$option_Att_selected = 'selected="selected"';

}

echo ' <option value="' . $opt_value . '" ' . $option_Att_selected . '>' . $opt_value . '</option>';

}

?>

</select>

<button class="submit" type= "submit" value= "Submit"> Submit Form </button>

</form>

</body>

</html>

Link to comment
Share on other sites

Hello dsonesuk, was trying to code a multiple checkbox array for the form above. Cant figure out the problem in the code below? Kindly assist..

 

HTML code

Which type of laptop would you like us to deliver to you? <span class= "error"> * </span>

 <br> <br> <input type="checkbox" class="input" name="checkbox[]" value="HP"> H.P <br>
                <input type="checkbox" class="input" name="checkbox[]" value="DELL" > DELL <br>
                <input type="checkbox" class="input" name="checkbox[]" value="ACER" > ACER<br>
                <input type="checkbox" class="input" name="checkbox[]" value="TOSHIBA" > TOSHIBA

PHP code

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Check Checkbox
	if(!empty($_POST["checkbox"])){        

            $checkboxErr = "Please Select one of these options";
          } else {
		$checkbox = test_input($_POST["checkbox"]);}
		
		$array = ["HP", "DELL", "ACER", "TOSHIBA"];
}
?>
Link to comment
Share on other sites

Checkbox index and value will refer to an array of values, whereas you would send a single value to be checked using test_input() you will be sending not a single value but array of values, and that will cause it to fail.

 

You should loop through the array of values, and send each of those single values to test_input() function.

Link to comment
Share on other sites

This way

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Check Checkbox
	if(!empty($_POST["checkbox"])){
             $value=false;
			 
            foreach($_POST["checkbox"])
			
            $checkboxErr = "Please Select one of these options";
          } else {
		$checkbox = test_input($_POST["checkbox"]);}
		
		$array = ["HP", "DELL", "ACER", "TOSHIBA"];
}
?>
Link to comment
Share on other sites

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Check Checkbox
	if(!empty($_POST["checkbox"])){
             $value=false;
			 
            foreach($_POST["checkbox"] as $selected)
	 foreach ["HP", "DELL", "ACER", "TOSHIBA"];
            $checkboxErr = "Please Select one of these options";
          } else {
		$checkbox = test_input($_POST["checkbox"]);}
}
?>

How about that? Am not sure of it,,Could you explain using an example so as to follow easily

Link to comment
Share on other sites

// Check Checkbox
	if(!empty($_POST["checkbox"])){
             
			 
			 $checkbox = array("HP", "DELL", "ACER", "TOSHIBA"); 
			 
			 foreach ($checkbox as $value) {
                 echo "$checkbox";
			 }
            else {
		$checkbox = test_input($_POST["checkbox"]);}
}

Followed the tutorial. But still can't get it post the values in my inbox..

Link to comment
Share on other sites

 

I've looked around for a few examples and followed the tutorials here but a lot of them are either too advanced for my grasp of PHP as abeginner or their examples are too specific to their own projects. Here's my new snippet


// Check Checkbox

if(!empty($_POST["checkbox"])){

$checkbox = $_POST['checkbox'];

foreach ($_POST["checkbox"] as $value) //loop to store and display values of individual checkboxes

{echo "$value";

}

else{$checkbox= test_input($_POST["$value"]);}}

 

 

Link to comment
Share on other sites

I'll go through this one more time

 

(1) test_input(); can ONLY process a single value at a time.

(2) $_POST['checkbox']; being a index ref to checkbox name attribute value can possibly have multiple values, as an array would, much like array("HP", "DELL", "ACER", "TOSHIBA");

(3) $checkbox = $_POST['checkbox']; will refer to values stored in $_POST['checkbox']; as if it refers to array.

(4) foreach ($checkbox as $value) will loop through all possible SINGLE values and assign it to variable $value in sequence, THIS is what should be passed with the function test_input() as a parameter for validation.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...