从SQL下拉列表中将值插入变量

时间:2016-12-18 01:59:10

标签: php mysql sql forms html-form

我试图从MySQL数据库中获取数据并将其放入下拉列表中,然后获取该数据并将其放入变量中。 但变量最终具有空值

<!--create a drop down list that contains all the classes-->
<form name="booking" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
    <select name="class">
        <?php
        // fetches all classes from db
        $sql = "SELECT class_name FROM class";
        $result = mysqli_query($con, $sql);


        while($row = mysqli_fetch_array($result)) {
            //Take in all the classes from the database
            echo '<option value=' . $row["class_ID"] . '>' . $row["class_name"] . '</option>';
        }
        ?>
    </select>
    <!--close the drop down list-->
    <br>
    <button type="submit" name="submit_button" class="btn btn-primary">Select Class</button>

    <?php
    if(isset($_POST["submit_button"])) {
        //Input the value from the while loop into the $class variable
        $class_name = $row['class_ID'];
        $sql = "SELECT * FROM class where class_name =$class_name";
    }
    ?>
</form>
</body>
</html>

目前所有$ class_name变量都是NULL但我希望它从数据库中取值class_ID。

1 个答案:

答案 0 :(得分:0)

在5.行中,您使用select查询,只从db'class_name'

中获取1个字段

在9.行中你想从db 1调用2个字段:'class_ID'和2:'class_name'

在20.行中你定义了$ class_name = $ row ['class_ID'];但它将返回null,因为你在5.行

中调用了1个字段

请查看下面的代码。

<form name="booking" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
    <select name="class">
        <?php
        // fetches all classes from db
        $sql = "SELECT class_name,class_ID FROM class";
        $result = mysqli_query($con, $sql);

        while($row = mysqli_fetch_array($result)) {
            //Take in all the classes from the database
            echo '<option value=' . $row["class_ID"] . '>' . $row["class_name"] . '</option>';
        }
        ?>
    </select>
    <!--close the drop down list-->
    <br>
    <button type="submit" name="submit_button" class="btn btn-primary">Select Class</button>

    <?php
    if(isset($_POST["submit_button"])) {
        //Input the value from the while loop into the $class variable
        $class_name = $_POST['class'];
        $sql = "SELECT * FROM class where class_name =$class_name";
    }
    ?>
</form>
</body>
</html>