php while循环显示sql数据不正确

时间:2013-11-18 02:20:10

标签: php html mysql

好的,我有这个while循环基本上从SQL DB中获取数据并将其放入下拉菜单,问题是为每个值创建了一个单独的下拉列表。我只需要一个下拉列表即可显示所有值。

<!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>

3 个答案:

答案 0 :(得分:2)

您需要在while循环之外移动select元素的print语句:

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>";

为了省去另一个问题,您需要抛弃value属性,否则每个选项都会提交相同的值,因为它们都设置为1。虽然更好的选择可能是打印学校的ID:

$data = "select schoolId, schoolName from schooltable";

print '<option value="'.$row['schoolId'].'">'.$row['schoolName'].'</option>';

答案 1 :(得分:1)

每次你再次绕过循环,你就会创建一个新的html元素。它应该是:                         无标题文档     

<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>

答案 2 :(得分:0)

这应该是它应该看起来的样子,也避免使用mysql_前缀函数。使用mysqli_的OOP版本的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>";