How to Create a Dynamic Drop Down List in PHP populated from MySQL Database

38,143

Solution 1

Get rid of the inner foreach loop... it is doing nothing for you and move the start and end select tags outside of the while loop.

$select_query=          "Select name from category";
$select_query_run =     mysql_query($select_query);
echo "<select name='category'>";
while ($select_query_array=   mysql_fetch_array($select_query_run) )
{
   echo "<option value='' >".htmlspecialchars($select_query_array["name"])."</option>";
}
echo "</select>";

Solution 2

<?php

$res = mysqli_query($conn, "SELECT DISTINCT coloumn_name FROM table_name;" );
while($row = mysqli_fetch_array($res))    
{
    echo "<option value='" . $row['selected_coloumn']. "'>" . $row['selected_coloumn'] . "</option>";
}
?>

In this example please select your 'coloumn_name' and 'table_name'.

Solution 3

take look at this code.

$select_query=          "Select name from category";
$select_query_run =     mysql_query($select_query);

echo "<select>";
while   ($select_query_array=   mysql_fetch_array($select_query_run) )
{
        echo "<option value='' >".$select_query_array['name']."</option>";                        
}
echo "</select>";
Share:
38,143
Taha Kirmani
Author by

Taha Kirmani

#SOreadytohelp

Updated on August 01, 2020

Comments

  • Taha Kirmani
    Taha Kirmani almost 4 years

    I am trying to create a dynamic drop down list using PHP and mysql database. I have written the following code and its giving me the output, but the problem is that its showing different drop-down menu for each item, I want all items in a single drop down list. Kindly check it and guide me.

            $select_query=          "Select name from category";
            $select_query_run =     mysql_query($select_query);
            while   ($select_query_array=   mysql_fetch_array($select_query_run) )
            {
                foreach ($select_query_array as $select_query_display)
                {
                    echo "  
                        <select>
                            <option value='' >$select_query_display</option>                        
                        </select>
                    ";
    
    
                    }
    
                }
    

    Thanks

  • Taha Kirmani
    Taha Kirmani almost 11 years
    Thank you so much for the prompt response! It is working !! :)
  • Taha Kirmani
    Taha Kirmani almost 11 years
    It is working, but its showing duplicate records. I didn't give it negative points. Thanks :)