Request Brochure

Blog & News

Populating a Combo-box in PHP Dynamically from MySQL

For this article, let's pretend you have the following database table. There are two columns (I'm separating the fields with commas for readability), Item and Price:

Cheese Pizza, 1.00
Pepporoni Pizza, 1.50
Sausage Pizza, 1.50
Cheese Calzone, 1.50
Ham Calzone, 2.00

What if you want to populate a combo-box with your possible options? We can write php that generates a drop-down box that has five item choices in it, based on our table above. Here is the sample code:

<?php

  // Connect to the database
  mysql_connect("localhost", "user", "password") or die(mysql_error());
  mysql_select_db("name") or die(mysql_error());

  // Has the form been submitted?
  if (isset($_POST['item'])) {

    // The form has been submitted, query results
    $queryitem = "SELECT * FROM table WHERE item = '".$_POST['item']."';";

    // Successful query?
    if($result = mysql_query($queryitem))  {

      // More than 0 results returned?
      if($success = mysql_num_rows($result) > 0) {

        // For each result returned, display it
        while ($row = mysql_fetch_array($result)) echo $row[serial];
      }
      // Otherwise, no results, tell user
      else { echo "No results found."; }
    }
    // Error connecting? Tell user
    else { echo "Failed to connect to database."; }
  }
  // The form has NOT been submitted, so show the form instead of results
  else {

    // Create the form, post to the same file
    echo "<form method='post' action='example.php'>";

    // Form a query to populate the combo-box
    $queryitem = "SELECT DISTINCT item FROM table;";

    // Successful query?
    if($result = mysql_query($queryitem))  {

      // If there are results returned, prepare combo-box
      if($success = mysql_num_rows($result) > 0) {
        // Start combo-box
        echo "<select name='item'>n";
        echo "<option>-- Select Item --</option>n";

        // For each item in the results...
        while ($row = mysql_fetch_array($result))
          // Add a new option to the combo-box
          echo "<option value='$row[item]'>$row[item]</option>n";

        // End the combo-box
        echo "</select>n";
      }
      // No results found in the database
      else { echo "No results found."; }
    }
    // Error in the database
    else { echo "Failed to connect to database."; }

    // Add a submit button to the form
    echo "<input type='submit' value='Submit' /></form>";
  }
?>
  • Mir Hussain Raza Talpur

    having problem with this it says failed to connect to database even though i have listed the database names i have database users and 2 tables Item and Price. then why its saying failed to connect to database user password is also correnct. help me out with this example.

  • KenK

    One way to test if you are properly connecting to your database is to try the connect lines and leave everything else out:

    mysql_connect(“localhost”, “user”, “password”) or die(mysql_error());
    mysql_select_db(“name”) or die(mysql_error());

    If you get an error message from just those two lines, then you know the error is related to the connection information you are supplying.

  • Torolf Rönnberg

    Hi!
    Nice basic work BUT, what if you would like to have a link added to combo-box results? How would it then look like? I mean for each item in the combo-box.

  • Lucho

    thank you very much! works like a charm! :)

  • Khan

    Thanks mate .. been looking for it as my code was not working properly and couldn’t find it any where else.
    Any idea how can we make two linked dropdowns i.e DD-A select country and DD-B loads cities from database .. I know one has to use Onchange tag but any example would be great.
    Thanks

  • john

    Your code doesn’t work at all..It displays “no result found”. I tried each and everything.

    Let me know what is wrong in the code given below:

    0) {

    // For each result returned, display it
    while ($row = mysql_fetch_array($result)) echo isset ($row['serial']);
    }
    // Otherwise, no results, tell user
    else { echo “No results found.”; }
    }
    // Error connecting? Tell user
    else { echo “Failed to connect to database.”; }
    }
    // The form has NOT been submitted, so show the form instead of results
    else {

    // Create the form, post to the same file
    echo “”;

    // Form a query to populate the combo-box
    $queryitem = “SELECT DISTINCT item FROM itemprice”;

    // Successful query?
    if($result = mysql_query($queryitem)) {

    // If there are results returned, prepare combo-box
    if($success = mysql_num_rows($result) > 0) {
    // Start combo-box
    echo “n”;
    echo “– Select Item –n”;

    // For each item in the results…
    while ($row = mysql_fetch_array($result))
    // Add a new option to the combo-box
    echo “$row[item]n”;

    // End the combo-box
    echo “n”;
    }
    // No results found in the database
    else { echo “No results found.”; }
    }
    // Error in the database
    else { echo “Failed to connect to database.”; }

    // Add a submit button to the form
    echo “”;
    }
    ?>

Featured

Channels

Authors

About iD Tech

iD Tech is the #1 tech camp on the planet! Kids and teens design video games, mod with Minecraft, code apps, engineer robots, build websites, produce films, and more. 100+ locations nationwide with hand-selected staff, unique campus experiences, and stimulating courses delivered in small clusters of 8 students per instructor.

Show all iD Tech Locations Show all iD Tech Courses