从mysql数据库填充Php下拉列表

时间:2017-04-10 23:00:08

标签: php mysql

我正在尝试从mysql数据库表中填充下拉列表

这是代码

<div class="form-group">
                Select Make
                        <?php
                            include '../db_config/dbcon.php';
                            $sql = "SELECT * FROM vehicle_details";
                            $result = mysql_query($sql);

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

这是代码显示的内容 dropdown screenshot

我哪里出错?

2 个答案:

答案 0 :(得分:0)

取决于dbcon.php中的内容,但这是使用mysqli_query的示例:

<div class="form-group">
    Select Make <?php
    // start of dbcon
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";


    $conn = new mysqli($servername, $username, $password, $dbname);
    //end of dbcon

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM vehicle_details";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        echo "<select name='vehicle_make'>";
        // output data of each row
        while($row = $result->fetch_assoc()) {
          echo "<option value='" . $row['vehicle_make'] . "'>" . $row['vehicle_make'] . "</option>";
        }
        echo "</select>";
    } 
    $conn->close();
    ?>
</div>

答案 1 :(得分:0)

这也有效,它是janlindo上面的修改

                 <div class="form-group">
                                    Select Make <?php
                                    include '../db_config/dbcon.php';
                                    $sql = "SELECT * FROM vehicle_details";
                                    $result = $conn->query($sql);
                                    if ($result->num_rows > 0) {
                                        echo "<select name='vehicle_make'>";
                                        // output data of each row
                                        while($row = $result->fetch_assoc()) {
                                          echo "<option value='" . $row['vehicle_make'] . "'>" . $row['vehicle_make'] . "</option>";
                                        }
                                        echo "</select>";
                                    } 
                                    ?>
                                </div>