dpd7195 2013-11-29 21:27
浏览 18
已采纳

链接两个php动态下拉列表

I'm in need of a bit of help >_<. I have two tables:

The first table which populated with car manufacturers called list_vehicle_marks with the columns

id | value

The second table, populated with car models called list_vehicle_models and has the following columns;

id | value | mark_id

The column mark_id has the same value as id in the first table, in other words, Ford has the id no. 37 and all Ford models have the mark_id as 37 too.

How would I create two dynamic dropdown menus, where the second menu shows only the models based on the manufacturer selected in the first menu?

This is what I have done so far:

<?php

connection to host, db, blah blah

if ($db->connect_error) {
echo "Failed to connect to MySQL: (" . $db->connect_error . ") "
. $db->connect_error;
} else {
$sql = "SELECT value FROM list_vehicle_marks";
$result_db = $db->query($sql);
if (!$result_db) {
    echo $db->error . ' Error perform query!';
} else {
    echo '<select name="value">';
    echo '<option value="">Select...</option>';
    while ($row = $result_db->fetch_object()) {
        echo '<option value="' . $row->value . '">';
        echo $row->value;
        echo '</option>';
    }
    echo '</select>';
}
}
$db->close(); 
?>
  • 写回答

1条回答 默认 最新

  • dongyue7796 2013-11-29 21:39
    关注

    In the code you posted, the drop down that you create, it should be something like this

    echo '<option value="' . $row->id. '">';
    echo $row->value;
    echo '</option>';
    

    Notice the $row->id instead of $row->value

    To Populate the corresponding dropdown you have two options:

    1. Once a user selects a value from the marks drop down you trigger a PHP function which gets the values of the corresponding vehicle models and re-render the page (You capture the id selected by the user using javascript)

    2. You fetch all the vehicle models along with vehicle marks (add another query to your above code that fetches all the models), keep the result of the models query in a JavaScript variable and generate the second dropdown using javascript once a user makes a selection. Here too you capture the users selection and call a javascript function that spits out a corresponding id drop down.

    The second method would not be a good option if your models table has a lot of data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)