我想添加一个动态选择列表,其中包含来自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>
编辑:
所以我试图在用户首次包含数据时将select选项放入。我试过的是
<?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>";
}
}
mysql_close($conn);
?>
但它没有显示导师表中的任何内容。是我的代码不正确还是我的mysql数据库问题?
答案 0 :(得分:0)
你应该从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>";
}
}