表单提交后未加载HTML选项标记

时间:2014-08-26 08:32:58

标签: php html forms

我有一个html页面,它使用PHP从MySQL表中加载select标签中的酒店列表。 select标记位于form标记内。每当我加载页面时,都会加载option标记,但是当我提交form时,option标记将不再加载。我的form action属性为空,我检查同一页面上的所有内容,但当我将另一个php页面设为action时,它会正常加载。有没有办法在提交后加载,同时保持form action为空?

这是我的代码

<?php

require_once 'db.php';

$db = DB::get_instance();

if(isset($_POST['search'])) {
    $hotel = $_POST['hotel_list'];

    $db->query("SELECT * FROM hotels WHERE Name='$hotel'");
    $hotel = $db->result()->current();

    $hid = $hotel['Hid'];

    $db->query("SELECT * FROM rooms WHERE Hid='$hid'");
    $rooms = $db->result();

    $db->disconnect();
}

?>

<!doctype html>

<html>
    <head>
        <title>Display a hotel</title>
    </head>
    <body>
        <form action="" method="post" id="dsphtl">
            Name: <select name="hotel_list" form="dsphtl">
<?php
            $db->query("SELECT Name FROM hotels ORDER BY Name");
            foreach($db->result() as $row) {
                $t = $row['Name'];
                echo "<option value='$t'>$t</option>";
            }
?>
            </select>
            <input type="submit" value="Search" name="search">
        </form>
    </body>
</html>

2 个答案:

答案 0 :(得分:4)

如果设置了$_POST['search'],则表示您$db->disconnect();,因此无法在表单中运行查询。

$db->disconnect();语句中取出if(),并将其放在文件的末尾。

答案 1 :(得分:1)

问题是断开连接,当页面重新加载后提交你的连接到mysql由于

而丢失
$db->disconnect();

<?php

    require_once 'db.php';

    $db = DB::get_instance();

    if(isset($_POST['search'])) {
        $hotel = $_POST['hotel_list'];

        $db->query("SELECT * FROM hotels WHERE Name='$hotel'");
        $hotel = $db->result()->current();

        $hid = $hotel['Hid'];

        $db->query("SELECT * FROM rooms WHERE Hid='$hid'");
        $rooms = $db->result();
    }

    ?>

    <!doctype html>

    <html>
        <head>
            <title>Display a hotel</title>
        </head>
        <body>
            <form action="" method="post" id="dsphtl">
                Name: <select name="hotel_list" form="dsphtl">
    <?php
                $db->query("SELECT Name FROM hotels ORDER BY Name");
                foreach($db->result() as $row) {
                    $t = $row['Name'];
                    echo "<option value='$t'>$t</option>";
                }
    ?>
                </select>
                <input type="submit" value="Search" name="search">
            </form>
        </body>
    </html>