Kategori
PHP

Create Dynamic Combobox Form from Database (Mysql) with PHP

Case Study : Create dynamic combobox with dynamic value
Requirements : Webserver Packages, already installed.

Combobox is one element in a form that is often used in applications – the application registration, generally combobox is used to select one option where there are many options available. Value in the combobox can actually be written directly in the html, but, what if the data you want to appear very much or depend on certain conditions?
Suppose, we want to show the choice of cities – cities that exist within the Indonesian state, the city is also a city which appears to be in Indonesia.
For example, a user was coming from England, the town which is also a city which appears to be in the UK.

We need dynamic combobox

Then, here we go.

Step 1 : Prepare the Database

  1. Create database named db_tutorial
  2. Prepare a table named tb_kota, with structure like picture below,
  3. Insert some sample data like below,
  4. Done!

Step 2 : Prepare the work directory

  1. Create folder named tutorphp in your document root
  2. Save all file in this tutorial in this folder.

Step 3 : Create a connection to DB script

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    $host = "localhost";
    $user = "root";//adjust according to your mysql setting
    $pass = ""; //adjust according to your mysql setting, i use no password here
    $dbName = "db_tutorial";
    mysql_connect($host, $user, $pass);
    mysql_select_db($dbName)
    or die ("Connect Failed !! : ".mysql_error());
    ?>
    [/sourcecode]
  2. Save with the name connect.php

Step 4 : Create the combobox form

  1. Type the following script,
    [sourcecode language=”php”]
    <form name=’form’ method=’post’ action=’prosescombo.php’>
    <h3> Choose Your City</h3>
    <select name="kota">
    <option value=0 selected>- city -</option>
    <?php
    include ‘connect.php’;
    $q = mysql_query("select * from tb_kota where negara = ‘Indonesia’ "); //choose the city from indonesia only

    while ($row1 = mysql_fetch_array($q)){
    echo "<option value=$row1[kota]>$row1[kota]</option>";
    }
    ?>
    </select>
    <input type="submit" name="submit" value="Submit">
    </form>
    [/sourcecode]

  2. Save with the name formcombo.php

Step 5 : Create script to show the result

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    $kota = $_POST[‘kota’];

    if ($kota == ‘0’) {
    echo "anda belum memilih";
    } else
    echo "anda memilih ".$kota;
    ?>
    [/sourcecode]

  2. Save with the name prosescombo.php

Step 6 : Testing Code

  1. Go to http://localhost/tutorphp/formcombo.php. You will see the form like below. Choose one option (i choose Solo, here).
  2. Choose submit. And see the result 😀

OK. Haaaaaaaapppy Coding! 😀