php - 使用来自 php 的值将新选项添加​​到 select 中

标签 php html mysql html-select

我想添加一个动态选择列表,其中包含我来自 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/

相关文章:

java - 分层mp3音轨

php - 带有复杂 $textField 的 CHtml::listData

php - MySQL : Problem in exporting the database

php - 在 PHP/MySQL 中使用数组

html - 将{位置: absolute;} always position my element with respect to its first parent?

html - 是否有任何纯 html 方法将 "combine"标记标记转换为自定义标记?

php - 带有日期类型的自定义字段的 Wordpress 查询

css issue- span 和 anchor 即使没有高度或宽度也会导致额外的边距

mysql - SQL QUERY - UNION - 多个相同的表需要很长时间

php - 在 jquery 中引用一个 php 字符串?