PHP中的服务器端级联下拉菜单 [英] Server side cascading dropdown in PHP

查看:166
本文介绍了PHP中的服务器端级联下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我在第一个下拉列表中只有一个值,因此我试图在PHP中创建级联下拉列表,以填充页面加载中的第二个下拉列表。

我的数据库有一张名为'nights'的表,名为'city','name'和'day'。为了填充我的第一个框,我使用 SELECT DISTINCT从晚上的城市等工作正常。



要填充第二个盒子,我需要沿着 SELECT name WHERE city = $ city - 我的问题是我不知道如何设置 $ city < select> 标签)。我无法使用 $ _ POST ['city'] ,因为此时尚未发送表单。



<如果你想这是动态的(即在用户改变下拉菜单后),你将不得不以使用JavaScript首先查询PHP页面(可能使用 jQuery获取),然后相应地调整下拉菜单。网上有很多教程。



如果您只想填充初始页面数据,您可以从查询中选择第一个城市,并设置选项按照选择,然后在下一个查询中使用该城市。

类似于:

  $ first = True; 
while($ row = mysql_fetch_array($ result))
{
echo< option。 (($ first)?selected:)。 > 中。 $ row ['city']。 < /选项> 中;
if($ first)
{
$ first =!$ first;
$ city = $ row ['city'];


//现在用$ city


As I only have one value in the first dropdown, I am trying to create a cascading dropdown in PHP that populates the second dropdown on page load.

My database has a table called 'nights' with fields called: 'city', 'name' and 'day'.

To fill my first box I'm using SELECT DISTINCT cities from nights etc which has worked fine.

To fill the second box I need something along the lines of SELECT name WHERE city = $city - my problem is that I'm not sure how to set $city (being the name of the <select> tag). I can't use $_POST['city'] because the form hasn't been sent at this point.

Any ideas?

解决方案

If you want this to be dynamic (i.e. after the user changes the dropdown) you will have to use javascript to firstly query a PHP page (probably using jQuery get) then adjust the dropdowns accordingly. There are lots of tutorials for this on the web.

If you just want the initial page data to be populated you can pick the first city from your query and set the option as selected, then use that city in your next query.

Something like:

$first = True;
while($row = mysql_fetch_array($result))
{
    echo "<option" . (($first) ? " selected" : "") . ">" . $row['city'] . "</option>";
    if($first) 
    {
        $first = !$first;
        $city = $row['city'];
    }
}
//now do stuff with with $city

这篇关于PHP中的服务器端级联下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆