PHP: Drop Down List with Select

Populating a drop down list control <select> from a php array is easy, the following function would do it with a breeze. Assuming an array of IT companies:

$companies = array(
	'Microsoft' => 1,
	'Google' => 2,
	'Apple' => 3
);

Feed it as a parameter to the php function below:

function generateSelect($name = '', $options = array()) {
	$html = '<select name="'.$name.'">';
	foreach ($options as $option => $value) {
		$html .= '<option value='.$value.'>'.$option.'</option>';
	}
	$html .= '</select>';
	return $html;
}

with

$html = generateSelect('company', $companies);

you will get an HTML form select control as following:

<select name="company">
	<option value="1">Microsoft</option>
	<option value="2">Google</option>
	<option value="3">Apple</option>
</select>

With data selected from SQL database, you will first convert the SQL results rows to php array and then use it with the generateSelect() function to generate HTML select control drop down list.

33 thoughts on “PHP: Drop Down List with Select”

  1. I get that; however, when you use mysql to read the info in the drop-down box, how to mark as selected without hardcoding something directly into html?

  2. do you know how to change drop down list value when another drop down list changed?

    something like this:
    i have 2 drop down list,,
    the 1st one is handphone brand
    the 2nd one is mobile type..

    the 2nd drop down list value depends on the 1st drop down list.
    both of the drop down list got the value from mysql DB.

    thx

    1. Please let me know too because I also want to do that.

      When selecting a Category, Products of that selected category show in next drop down.

      Please anyone..help
      e-mail: [email protected]
      please please please !

  3. I’m not sure how I’m supposed to get the dropdown box. Do I use
    $html = generateSelect(‘company’, $companies);
    or

    Microsoft
    Google
    Apple

  4. does one have to use a mysql db to email from a drop down box in php format.
    this is a small very efficent bit of coding .. thanks.
    EriK

    1. what i mean is if the drop down box has values like yours 1-3 and the options are email addresses/names of people to email. does one need a db and if so what are the field names in the db ..name/email/value?? if you could help or ask for a clearer statement from me a newbie please ask. help is greatly needed and appreciated

        1. thanks but that’s Greek to me. not sure what you are suggesting? do you mean i need a db and then how do i connect to it and what fields do i add to db and how to link to db to select email addresses i haven’t a clue.

  5. Hye..i want create a simple dropdown list from D1 until D20 using ‘ARRAY PHP’ with database but i dont know how to create that.can u explain me from begin?now im already created db.my db name is “line1” and my form name is “chip”.i hope u can show me step by step because i dun know about programming.

  6. hi i’m new in doing php right now, i have my first task, there is already an existing program but what i need to revise is a drop down just like the comment of sucipto in this thread, the difference is that for example when the user select registered, the next text box will be enable for the input of registration NO., if he chose as not registered then the textbox will be disabled.Thank you for your help and will be highly appreciated.

  7. $companies = array(
    ‘Microsoft’ => 1,
    ‘Google’ => 2,
    ‘Apple’ => 3
    );

    Using your example, is it possible to have this drop down list, for example, load up with ‘Apple’ (option #3) being PRE-selected?

  8. Useless tutorial for beginners when you don’t bother to show a “complete” preview on how it should be done.

    Beginners has no way to understand what you mean by
    “$html = generateSelect(‘company’, $companies);”

  9. You you could change the blog subject title PHP: Drop Down List with Select to more specific for your webpage you write. I liked the the writing yet.

  10. Hello

    I have create some forms on PHP. Now I want to put them as a drop down one page, such as when i click on documents I must have a drop down of all the forms that I did, so that I can choose from there the form that I need. Please help.

  11. Hiya!

    I am trying to use a drop down list to select a page to include depending on the option, so it is: out of the option list of “Mine”, “his” “its”, i would like that when i select “Mine” from drop down list it uses
    include=(“myflie.php”);
    although if i choose “his”, then it includes his.php
    include =(“his.php”);

    is this possible?

    thanks guys!
    andrea

  12. Good Evening Sir,
    This is Mohammad Ajmal, from Hyderabad, INDIA, I need one guidence from you if you will do that so my work will be easy so please guide me and I will be very thanksfull of you.
    I want to create a programe of Dropdown list in HTML, In that what I want, in first drop down list I want to select class from 1st to 5th, if I will select 1st class from dropdown list so I want the dropdownlist of 1st class students names list below first dropdown list but if I will select 2nd class so I want 2nd class students names list.
    So please guide me with your experience. I am waiting for your reply.
    Thanks and Regards
    MOHAMMAD AJMAL

  13. How would you generate a drop down when you don’t know whtat the choices are(i.e. getting the choices from a table via mysql_query and then putting those values into an array

    1. Essentially you would use php to query the data base.
      Example of Connection:
      // create connection
      $MySQLserver = “localhost”;//the server of the MySQL (ie, localhost)
      $username = $_POST[‘username’]; //the username for the DB (ie, root, web, whatever)
      $password = htmlspecialchars($_POST[‘password’]); //the password for that username
      $DBname = $_POST[‘DBname’];
      $connection = mysql_connect(“$MySQLserver”,”$username”,”$password”);
      // select database
      // change DBname to the DB that you are using
      $db = mysql_select_db(“$DBname”, $connection);
      // create SQL statement
      // you will need to create the select statement
      $sql = “select …….”
      // submit the select statement
      $sql_result = mysql_query($sql,$connection);

      //get results you want to add to the select array
      //there are lots of ways to do this but this is just one way
      foreach($sql_result as $keynumber => $keyvalue)
      {
      // we are going to store the data in a string and then convert to array
      $mydata .= $mydata + $keyvalue[‘column name’]+’#’;
      }
      $companies = preg_split(‘#’,$mydata);
      And then you would just pass $companies as in the posted example.

  14. I tried to modify your function to minimize user interaction and select the appropriate department (based on referrer) from the list. When doing so, it selects the appropriate option, then each option thereafter… Any thoughts?

    function generateSelect($name = ”, $options = array(), $selected) {
    $html = ”.”\n”;
    foreach ($options as $option => $value) {
    if($selected==$value){$select=’selected=”selected”‘;}
    $html .= ”.$option.”.”\n”;
    }

    $html .= ”.”\n”;
    return $html;
    }

  15. I am trying to develop a system where a user can edit his or her listed property.That means extracting the information back, update it and resubmit it..But my problem is that i have not been able to retrieve the information that where posted from a dropdown menu..Could you assist me on this??

  16. how can we make dynamic drop down list like fist select country name then automatic comes state name in state drop down list. Please reply me on my email address

  17. Hi,

    I am new to PHP and tried the following which did not work.
    Can you explain why ?

    <?php

    function generateSelect($name = '', $options = array())
    {
    $html = '’;
    foreach ($options as $option => $value)

    {$html .= ”.$option.”;}

    $html .= ”;
    return $html;
    }

    $companies = array(
    ‘Microsoft’ => 1,
    ‘Google’ => 2,
    ‘Apple’ => 3);

    $html = generateSelect(‘company’, $companies);

    ?>

  18. Hi,

    Can someone advise how to implement a dropdown of yes/no in “Attending” in the following form:
    ___________________________________________________

    $action = $_SERVER[‘PHP_SELF’].”?module=”.$_GET[‘module’];

    // (label, required)
    // (E-mailadres needs to be there because of sender)

    $form_fields = array(
    array(“Attending”),
    array(“Full name”, 1),
    array(“E-mail address”, 1),
    array(“Telephone number”, 1),
    array(“Additional guests”, 0),
    );

    if(isset($_POST) && $_POST[‘action’] == “add”)
    {
    foreach($form_fields AS $formrow)
    {
    if ($formrow[1])
    {
    if(trim($_POST[strtolower(str_replace(” “, “_”, $formrow[0]))]) == “”)
    {
    $melding.= “- “.$formrow[0].” has not been completed\n”;
    $errors++;
    }
    }
    }
    if (!$errors)
    {
    $to = “[email protected]”;
    $from = $_POST[‘e-mail address’];
    $subject = “Contactform – Engagementparty Joy & Chaggai\n\n”;
    $headers = “From: “.$from.”\n”;
    mail($to, $subject, print_r($_POST, true), $headers);
    $succes++;
    $melding = “THE FORM HAS BEEN SENT SUCCESSFULLY.“;
    }
    }
    if ($errors || $succes)
    {
    echo “”.$melding.””;
    }
    ?>
    <form action="” method=”post”>

    <?php
    foreach($form_fields AS $formrow)
    {
    $label = $formrow[0];
    $value = "";
    if (isset($_POST[strtolower(str_replace(" ", "_", $formrow[0]))]))
    {
    $value = $_POST[strtolower(str_replace(" ", "_", $formrow[0]))];
    }
    echo "\n”;
    echo “”.$label.” : \n”;
    echo “”;
    printf(“”;
    if ($formrow[1])
    {
    echo ” *”;
    }
    echo “\n”;
    echo “\n”;
    }
    ?>

     

    *fields are obligated
    ______________________________________________________________

    Thank you so much!

  19. select ID
    <?php

    $con=mysql_connect("localhost","root","");
    mysql_select_db("sky",$con);
    $result=mysql_query("select name from salary",$con);
    //echo "”;
    //echo “selectID”;
    while($row=mysql_fetch_array($result))
    {
    $id=$row[‘name’];
    //echo “”.$id.””;

    }
    //echo “”;
    ?>

  20. Amitabh Deotale

    <Select name= style= id=>
    Select Any

    <option value='’Selected>

    <option value='’>

  21. Hello sir,
    This is Manish , from Indore, INDIA, I need one guidence from you
    I want to create a programe of Dropdown list in HTML, In that I want, in first drop down list I want to select class 1st, if I will select 1st class from first dropdownlist so I want the dropdownlist of 1st class students names list in second dropdownlist and if I will select 2nd class so I want 2nd class students names list.
    So please guide me with your experience. I am waiting for your reply.
    Thanks and Regards
    Manish Verma

  22. when I edit a value from the same form as a values from a drop down list the values in the drop down list change back to the first set value.

    Can you please asist me here?

Comments are closed.

Scroll to Top