Populating a Combo-box in PHP Dynamically from MySQL

iD Tech in action

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
Pepperoni 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>";
  }
?>
A photo of Ryan

Ryan has been in EdTech and with iD Tech for 13 years—building experience, expertise, and knowledge in all things coding, game development, college prep, STEM, and more. He earned his MBA from Santa Clara University after obtaining his Bachelor’s degree from Arizona State. Connect on LinkedIn

Featured Posts

Categories

Authors

About iD Tech

iD Tech is the #1 tech camp on the planet, and world leader in youth STEM education, with programs held online and at 75+ global locations offering 50+ innovative tech courses: 

Coding camps
Video game camps
Robotics classes & camps
Creative arts classes & camps
All STEM camps

We've bet our reputation on recruiting the top instructors in the country. Our small classes ensure customized learning, leading to "a-ha moments" and awesome outcomes. Programs include:

On-Campus Programs

Online Tutoring

All Coding Courses