문제

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!

도움이 되었습니까?

해결책

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>';
  }
}

다른 팁

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>';
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top