我想添加一个动态选择列表,其中包含我来自 php 的数据。我该怎么做?我还想用其他 php 文件中的变量作为参数,例如 $mentor==$rows。欣赏
<th><select name="mentor" style="width:95%">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("testproject", $conn);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT mtrname FROM mentors";
$sql2 = "SHOW COLUMNS from mentors";
$result= mysql_query( $sql, $conn );
if(! $result)
{
die('Could not get data: ' . mysql_error());
}
$fetchrow = mysql_fetch_row($sql2);
$num = count($fetchrow);
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
$rows[$i];
}
}
mysql_close($conn);
?>
<option value="<?php echo $mentor?>" <?php if($mentor==$rows[i]) echo 'selected'?>><?php echo $mentor?></option>
</select></th>
编辑:
所以我试图在用户首次包含数据时将选择选项放入。我试过的是
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("testproject", $conn);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT mtrname FROM mentors";
$sql2 = "SHOW COLUMNS from mentors";
$result= mysql_query( $sql, $conn );
if(! $result)
{
die('Could not get data: ' . mysql_error());
}
$fetchrow = mysql_fetch_row($sql2);
$num = count($fetchrow);
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
echo"<option value='".$rows[i].">".$rows[i]."</option>";
}
}<br/>
mysql_close($conn);
?>
但它不显示导师表中的任何内容。是我的代码不正确还是我的 mysql 数据库有问题?
最佳答案
您应该从 mysql 迁移到 PDO 或 mysqli,因为它没有过时。如果返回的结果是正确的,那么你几乎就在那里。只需将 option
标记移动到 for()
循环中即可。
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
echo "<option value='$mentor'". ($mentor==$rows[i] ? 'selected' : '') .">$mentor</option>";
}
}
关于php - 使用来自 php 的值将新选项添加到 select 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30387976/