【问题标题】:Insert values into variables from SQL drop down list从 SQL 下拉列表中将值插入变量
【发布时间】:2017-05-03 10:55:54
【问题描述】:

我正在尝试从 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。

【问题讨论】:

  • 提交表单后,选择的(选择的)值应该在$_POST['class'] 内,我在您的代码中的任何地方都看不到它。

标签: php mysql sql forms


【解决方案1】:

在 5. 行中,您使用选择查询并且只从 db 'class_name' 中获取 1 个字段

在第 9 行中,您想从 db 1:'class_ID' 和 2:'class_name' 调用 2 字段

在 20.row 你定义 $class_name = $row['class_ID'];但它会返回 null,因为您在 5.row 中调用了 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多