【问题标题】:How to populate dropdown menu from sql table in PHP [duplicate]如何从PHP中的sql表填充下拉菜单[重复]
【发布时间】:2017-12-04 23:03:18
【问题描述】:

我尝试将其插入到我的代码中以通过 sql 表生成下拉菜单,但它在下拉列表中没有任何响应。当我执行 sql 查询时,它也没有显示任何错误。请善待解决我的错误。谢谢

 <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
            mysqli_query($db, $sql);

            echo "<select name='unitid'>";
            while ($row = mysql_fetch_array($sql)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>"; 
            }
            echo "</select>";
            ?>

【问题讨论】:

    标签: php html mysql drop-down-menu


    【解决方案1】:

    尝试保存mysqli_query的结果:

    $result = mysqli_query($db, $sql);
    

    然后在while条件下使用:

    while ($row = mysqli_fetch_array($result)) {
    

    select 也应该是 "Select unitid, unitname ..." 以返回选项中使用的 unitname:

    $sql = "SELECT unitid, unitname FROM unit WHERE unitname = '$unitname'";
    

    如果你想防止 SQL 注入攻击,你应该使用准备好的语句。

    如果您希望所有单位都显示在组合上,请将选择更改为:

    $sql = "SELECT unitid, unitname FROM unit";
    

    所以,代码现在应该是:

     <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select unitid, unitname from unit";
            $result = mysqli_query($db, $sql);
    
            echo "<select name='unitid'>";
            while ($row = mysqli_fetch_array($result)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>"; 
            }
            echo "</select>";
     ?>
    

    【讨论】:

    • 对不起,它似乎不起作用
    • 检查您的选择,因为 unitname = '$unitname' 只会返回一个结果。如果您希望所有单位都显示在下拉列表中,就像我想的那样,只需删除 where。
    【解决方案2】:
            <?php
             $db = mysqli_connect('localhost', 'root', '', 'registration');
              $sql = "Select unitid, unitname from unit where unitname=\"".$unitname."\"";
    
            $rows = array();
            $return = mysqli_query($db, $sql);
            while($row = mysqli_fetch_array($return, MYSQLI_ASSOC))
                $rows [] = $row;
            echo "<select name='unitid'>";
            for($i=0; $i<count($rows); $i++)
               echo "<option value='".$rows['unitid']."'> ".$rows['unitname']."</option>"; 
    
            echo "</select>";
            ?>
    

    您没有正确获取数组,因此您的查询基本上返回了一个空数组。您还写了一个错误的查询。这个解决方案应该可以正常工作

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多