Question

I have used a dropdown list which is populated with data from a database using a query but i can't seem to add a default value to the top of the list e.g. "Select Class". All DB data is being retrieved fine but cannot add any default title like Select Class.

function query(){
  $classes = mysql_query("SELECT * FROM class") or die("Could not search!");
  while ($row = mysql_fetch_array($classes)) {
    echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
  }
}

All help is much appreciated!

Was it helpful?

Solution

You need to add an <option> before you begin your loop.

function query(){

  // This is the line you are missing
  echo '<option>Select a class</option>';

  $classes = mysql_query("SELECT * FROM class") or die("Could not search!");
  while ($row = mysql_fetch_array($classes)) {
    echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
  }
}

OTHER TIPS

Just echo out the default option before the while loop starts:

$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
echo '<option value="">Select Class</option>';
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row["class_name"] . '</option>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top