dongliang2058 2015-02-18 19:36
浏览 37

如何根据用户选择从表中查找ID

So I am creating some php code for the add accommodation section of my website. The user is given the option of selecting a city from the drop down menu (the list is retrieved from the city table in the mysql database by using a simple query and echo). But what needs to be stored in the add accomodation table is the city ID and of course I can't be asking the user for that! What I can't figure out is how to query the city table using the selected city and retrieve the city ID from the same table and store that in the accommodation table in the backend database. Here is the code I have so far.

<?php
$query = "SELECT City_Name FROM Cities";
$result = mysql_query($query);
?>
<p>
<label for = "City_Name" class = "fixed_required">City: </label>
<select name="select_City" id="select_City" value="<?php if(isset($_POST['City_Name'])) echo $_POST['City_Name']; ?>"/>
</p>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['City_Name'];?>"> <?php echo $line['City_Name'];?> </option>
<?php
  • 写回答

1条回答 默认 最新

  • dongwei3866 2015-02-18 19:39
    关注

    Try this :

    value="<?php echo $line['City_ID'];?>"
    

    and change your query to include the ID :

    $query = "SELECT City_Name, City_ID FROM Cities";
    

    EDITED :

    Ok...you also need to set up the "SELECTED" attribute base on $_POST['select_City'] on the OPTION tag and remove the value="<?php if(isset($_POST['City_Name'])) echo $_POST['City_Name']; ?>" on the SELECT tag....And like @Dan Revah suggested, use MYSQLI instead since mysql is deprecated as of PHP 5.5.0

    <?php
    $query = "SELECT City_Name, City_ID FROM Cities";
    $result = mysql_query($query);
    ?>
    <p>
    <label for = "City_Name" class = "fixed_required">City: </label>
    <select name="select_City" id="select_City" />
    </p>
    <?php
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    ?>
    <option value="<?php echo $line['City_ID'];?>"  
    <?php
    if(isset($_POST['select_City'])) { 
        if(mysql_real_escape_string($_POST['select_City'])==$line['City_ID']) { 
           echo "selected"
        }
    }?>
    >
    <?php echo $line['City_Name'];?> </option>
    <?php
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用