首页 > 解决方案 > 从 MS SQL 数据库填充 Bootstrap 下拉列表

问题描述

我整个早上都在绞尽脑汁,通过谷歌搜索了很多页面。

我找不到用来自 MS SQL 服务器的数据填充引导按钮下拉框的方法。

有很多方法可以从 MySQL 中进行纯 HTML 下拉菜单。

这是按钮的代码:

<div class="btn-group">
    <button type="button" class="btn btn-info btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Family</button>
    <div class="dropdown-menu">
        <a class="dropdown-item" href="#">Option 1</a>
        <a class="dropdown-item" href="#">Option 2</a>
        <a class="dropdown-item" href="#">Option 3</a>
     </div>
 </div>

非常感谢您的帮助。

标签: phphtmlmysqlweb

解决方案


您不能使用 HTML 直接从 MySQL 填充下拉列表,因为您需要使用 PHP,因此如果您想从 MySQL 数据库中填充下拉项目,您可以访问您的数据库服务器端。

因此,您需要将 HTML 文件转换为 PHP 文件(index.html -> index.php),并且在其中您需要有类似的内容:

索引.php

<div class="btn-group">
    <button type="button" class="btn btn-info btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Family</button>
    <div class="dropdown-menu">
        <?php
            // server credentials
            $servername = "localhost";
            $username = "username";
            $password = "password";
            $dbname = "myDB";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            }

            // Replace with the desired SQL
            $sql = "SELECT options FROM MyOptions";
            
            // get the results
            $result = $conn->query($sql);

            if ($result->num_rows > 0) 
            {
                // output data of each row
                while($option = $result->fetch_assoc()) 
                {
                    // change "name" to the column fo your DB row.  
                    echo "<a class='dropdown-item' href='#'>".$option["name"]."</a> ";

                    // if you also store a link to your DB, for ex in a column link then use
                    // echo "<a class='dropdown-item' href='".option["link"]."'>".$option["name"]."</a> ";
                }
            } 
            $conn->close();
        ?>
     </div>
 </div>

推荐阅读