mdakic
mdakic

Reputation: 186

How to populate dropdown list from mysql db and based on selection populate another dropdown list in php form?

I have situation where i have column in mysql table from which i populate dropdown list for criteria for query for second dropdown list from another table. How coud i do that using php and selection of second dropdown list pass to another input form? I have same formBarkod column in both tables which is connection between tables data.

Upvotes: 0

Views: 5512

Answers (1)

Jake M
Jake M

Reputation: 544

This sounds like a job for javascript. You could populate each of the dropdowns with php and mysql, but you'd need javascript to have the selection on the first dropdown affect which of the next dropdowns is visible. The PHP and MySQL would look like this:

<?
//Assuming $dbh is a proper mysqli object...
$options = $dbh->query("SELECT * FROM options");

echo '<select id="firstDropdown">';
while($o = $options->fetch_object()) {
    echo '<option value="'.$o->id.'">'.$o->name.'</option>';
}
?>

Repeat that process for each dropdown.

Then you have to write some javascript to work on the change. I don't know enough "pure" javascript to do this, but I can show you what it'd look like in jQuery. Assuming your html looks like this:

<select id="firstDropdown">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>
<select id="dropdown1" class="dropdown">
    ...
</select>
<select id="dropdown2" class="dropdown">
    ...
</select>
<select id="dropdown3" class="dropdown">
    ...
</select>

Then the jQuery would look like this (all wrapped in a document.ready() of course)

$(".dropdown").hide();

$("#firstDropdown").on("change",function(){
    $(".dropdown").hide();
    var value = $("#firstDropdown").val();
    $("#dropdown"+value).show();
});

The basic flow is that you hide all of the secondary dropdowns. Then, whenever the value in the first dropdown changes, you rehide the secondary dropdowns, and show only the desired dropdown. You can do a lot more with this by actually creating the dom elements on the fly or by using an ajax call to get the new dropdowns, but this covers the basic concept.

EDIT: Here's a working example on jsfiddle.net

Upvotes: 1

Related Questions