Hi

I am using the following code to give the user a choice of options in a drop down box:

<?php 
 $query="SELECT location,id FROM area";
$result = mysql_query ($query);
echo "<select name=location_id value=''>location</option>";

while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[id]>$nt[location]</option>";
}
echo "</select>"; 
 
 ?>

It retrieves all of the options from a MySQl database.

How do I get it, so that the first option is blank, or says "Please Select"??

Thanks

Try this:

<?php 
$query="SELECT location,id FROM area";
$result = mysql_query ($query);
echo '<select name="location_id">';
echo '<optgroup disabled="disabled" style="margin-top: 1em;">Please select...</optgroup>';

while($nt=mysql_fetch_array($result)){
    echo "<option value={$nt['id']}>{$nt['location']}</option>";
}
echo "</select>"; 
 
 ?>

Hi

Thanks for the reply.

It creates a blank option which is first in the list, but it cannot be selected and you only see it when you use the drop down option.

Sorry, I put margin-top instead of margin-bottom.

Try now:

<?php 
$query="SELECT location,id FROM area";
$result = mysql_query ($query);
echo '<select name="location_id">';
echo '<optgroup disabled="disabled" style="margin-bottom: 1em;">Please select...</optgroup>';

while($nt=mysql_fetch_array($result)){
    echo "<option value={$nt['id']}>{$nt['location']}</option>";
}
echo "</select>"; 
 
 ?>

Thanks again, but it still does the same thing.

The first option from the database shows ie.London, and when you click on the drop down, there is a blank space at the top, but you are unable to select it.

Member Avatar for diafol

optgroup doesn't work like this.

<select ....>
    <option value="" disabled="disabled">Please select...</option>
    <option value="nextone">Next One</option>
    ....
</select>

sorry. knew it didn't look right, searched for "select disabled" and copied the code from one of my in development sites without thinking. hope you've accomplished what you were trying to achieve now :)

Simply like this:

<?php 
 $query="SELECT location,id FROM area";
$result = mysql_query ($query);
echo '<select name="location_id">';
echo '<option value="">Please Select..</option>';
while($nt=mysql_fetch_array($result)){
echo '<option value="'.$nt['id'].'">'.$nt['location'].'</option>';
}
echo '</select>'; 
 
 ?>
commented: Thanks for helping ... again ! +1

Thanks Emma

I thought I tried that yesterday, or it must have been very similar with something missing!!

Appreciate your help and the input of others

Thanks.This worked for me.

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.