Populating Php Dropdown list from mysql database

假如想象 提交于 2021-02-17 06:10:17

问题


am trying to populate a dropdown list from mysql database table

here is the code

<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>

This is what is displayed by the code

Where am i going wrong??


回答1:


Depending on whats in your dbcon.php, but here's an example using 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>



回答2:


This worked too, its a modification of janlindo's above

                 <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>


来源:https://stackoverflow.com/questions/43334180/populating-php-dropdown-list-from-mysql-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!