iD Tech Camps

Save money on camp with this special offer

Search Our Site

The World's #1 Tech Camp

iD News and Blog

Request a Brochure

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>";
  }
?>

March 31st, 2009 | Tags: , , , ,

Posted in: iD Tech Bloggers

5 Responses to Populating a Combo-box in PHP Dynamically from MySQL

  1. 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.

  2. Mir Hussain Raza Talpur on April 26th, 2009 at 1:18 pm
  3. 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.

  4. KenK on May 19th, 2009 at 8:34 am
  5. 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.

  6. Torolf Rönnberg on November 25th, 2009 at 2:08 pm
  7. thank you very much! works like a charm! :)

  8. Lucho on December 31st, 2010 at 7:03 pm
  9. This is an easy to use code to select records from MySQL database table and display in dropdown combo box using PHP.

    $cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
    mysql_select_db($db_name,$cn) or die(mysql_error());
    $sql = “SELECT field_name FROM table_name”;
    $rs = mysql_query($sql) or die(mysql_error());
    echo “”;
    while($row = mysql_fetch_array($rs)){
    echo “”.$row["field_name"].”";
    }mysql_free_result($rs);
    echo “”;

    Source:
    http://phphelp.co/2012/05/10/how-to-fill-a-dropdown-combo-box-in-php-from-mysql-database-table/

    OR

    http://addr.pk/a8cf

  10. Aneeq on May 10th, 2012 at 3:14 am

Leave a Reply

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

*

This entry was posted on Tuesday, Mar 31st at 09:30 am and is filed under iD Tech Bloggers. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Blog Categories

ACCED-I Meeting Exelence On CampusThe World's Best Summer Camps

Blog Archives

CEO's Blog

Tech Bloggers