Hello everyone,
Please help me to create a chained select box
here i created something , but when i select 1st one its load 2nd one's options from database, but get 1st one unselected

<form action="" method="post">
    Username: <br><select  name="productforuser" id="option" onchange="location = this.options[this.selectedIndex].value;">
                    <option selected  value="no_user_selected">No User Selected</option>
                    <?php 
                        $sql = "SELECT * FROM user";
                        $result = $conn->query($sql);

                        if ($result->num_rows > 0) {
                            while($row = $result->fetch_assoc()) {
                                echo "<option value='add_sale.php?user=$row[username]'>$row[username]</option>";  
                            }           
                        } 
                    ?>                          
                </select> <br>
    Product: <br><select  name="product" id="option">
                    <option selected  value="no_selected_product">No Product Selected</option>
                    <?php 
                        $username=$_GET['user'];
                        $sql = "SELECT * FROM products WHERE username='$username'";
                        $result = $conn->query($sql);

                        if ($result->num_rows > 0) {
                            while($row = $result->fetch_assoc()) {
                                echo "<option>" .$row['product_name']."</option>";
                            }           
                        } 
                    ?>  
            </select> <br>
        <input class="btn btn-default" type="submit" name="submit" value="Add" />
</form>

As i understand , you need to place a condition $selected , i have taken just country list so intid is primary key of table which is passing to url. hope this helps you.

$sql = "SELECT * FROM country";
                    $result = mysql_query($sql);
                    while ($row = mysql_fetch_assoc($result)) {

                        $selected = ($row['intid'] == $_GET['user']) ? 'selected="selected"' : '';
                        echo "<option value='chained.php?user=$row[intid]' $selected>$row[country_name]</option>";
                    }

`

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.