Reputation: 37
Ok, I have this while loop that basically grabs the data from an SQL DB and puts it into a dropdown menu, the problem is that a separate dropdown is created for each value. I need just one dropdown to display all the values.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost","root","")or die (mysql_error());
mysql_select_db("assignment_3", $conn);
$data = "select schoolName from schooltable";
$result = mysql_query($data, $conn) or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
print "<select>";
print "<option value='' disabled='disabled' selected='selected'> Please Select your Undergraduate School </option>";
print "<option value='1'>".$row['schoolName']."</option>";
print "</select>";
}
?>
</body>
</html>
Upvotes: 0
Views: 280
Reputation: 185
This is how it should look, also, avoid using mysql_
prefixed functions. Either use mysqli_
of the OOP version of MySQLi
.
$link = new mysqli( $host, $user, $password, $database ); // Connect to DB
$result = $link->query( "SELECT `schoolName` FROM `schoolTable`" );
echo "<select>";
echo "<option disabled="disabled" selected="selected">Please Select your undergraduate School</option>";
while ( $row = $result->fetch_assoc() ) {
echo "<option>" . $row['schoolName'] . "</option>";
}
echo "</select>";
Upvotes: 0
Reputation: 3261
Each time you go around the loop again you have it create a new html element. It should be: Untitled Document
<body>
<?php
$conn = mysql_connect("localhost","root","")or die (mysql_error());
mysql_select_db("assignment_3", $conn);
$data = "select schoolName from schooltable";
$result = mysql_query($data, $conn) or die (mysql_error());
print "<select>";
while ($row = mysql_fetch_assoc($result)) {
print "<option value='' disabled='disabled' selected='selected'> Please Select your Undergraduate School </option>";
print "<option value='1'>".$row['schoolName']."</option>";
}
print "</select>";
?>
</body>
</html>
Upvotes: 1
Reputation: 219934
You need to move the print statements for the select element outside of the while loop:
print "<select>";
print "<option value='' disabled='disabled' selected='selected'> Please Select your Undergraduate School </option>";
while ($row = mysql_fetch_assoc($result)) {
print "<option>".$row['schoolName']."</option>";
}
print "</select>";
To save you another problem, you'll need to ditch the value attribute or else every option will submit the same value because they're all set to 1
. Although a better option might be to print the id of the school instead:
$data = "select schoolId, schoolName from schooltable";
print '<option value="'.$row['schoolId'].'">'.$row['schoolName'].'</option>';
Upvotes: 2