基于动态HTML下拉列表运行不同的查询

时间:2014-10-01 18:18:06

标签: php html mysql

我制作了一些PHP代码来生成这个page。我成功地将列中的所有项目都放到HTML下拉列表中(这是一个动态列表)。我想编写一些代码,以便当用户从列表中选择一个项目并点击提交时,它将使用户在新页面中包含相应的信息。我不知道会包含哪种代码。请帮忙。谢谢!

例如,如果用户选择50A-1,它将填充一个表,其中所有项目都位于50A-1。

我写的两段代码,首先是页面为您提供下拉列表和提交按钮。第二个是结果页面,但它只显示到目前为止的整个库存,它没有办法连接到下拉列表选项。

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Inventory</title>
    </head>
    <body>
        <div>
            <a>SQL Connection test</a>
            <form action="connect.php" method="POST">
                <div class="center">
                    <input type="submit" value="Connect to MySQL" />
                </div>
            </form>
        </div>
        <div>
            <section>
                <article>
                    <p>
                        <select name="dropdown">
                            <?php query() ?>
                        </select>
                            <?php close() ?>
                    </p>
                </article>
            </section>
            <div>
                <input type="submit" value="Submit" />
            </div>
        </div>
    </body>
</html>

第二页

<?php
    include_once 'db.inc.php';
    // connect
    function connect() {
        // Connect to the MySQL server
        mysql_connect(DB_HOST,DB_USER,DB_PASS) or die ('Could not connect to server!' . mysql_error());
        mysql_select_db(DB_NAME);
    }
    // close
    function close() {
        mysql_close();
    }
    // query
    function query() {
        $myData = mysql_query("SELECT DISTINCT * FROM sheet0_100 GROUP BY location");
        while($record = mysql_fetch_array($myData)) {
            echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
        }
    }
?>

2 个答案:

答案 0 :(得分:1)

这就是HTML表单的目的:)

您需要创建一个表单来封装选择:

<form action="process.php" method="get">
    <select name="inventory_id">
        <!-- Here all options -->
    </select>
    <button type="submit">See items</button>
</form>

然后在process.php中,您需要获取所选元素并查询数据库,例如(我假设您正在使用PDO):

<?php
    $inventory_id = $_GET['inventory_id'] // The name attribute of the select
    // Then you prepare the query
    $query = "SELECT * FROM sheet0_100 WHERE id = :inventory_id";
    // Execute the query and show the data...

答案 1 :(得分:0)

使用Sessions

示例:

第一页

session_start();
$_SESSION['your-dropdown-list-value'] = 'Root';
新页面上的

//error_reporting(E_ALL);
session_start();
if(isset($_SESSION['your-dropdown-list-value'])) {
  echo "Your dropdown selection " . $_SESSION['your-dropdown-list-value'];
}