dtr53557
2013-03-03 15:57 阅读 59
已采纳

使用PHP和MySQL填充下拉列表

I am trying to populate a second dropdown list using the value selected from a first dropdown list using PHP and MySQL, and without refreshing the page. I thought this would be simple but can't get it to work so any help would be much appreciated.

So far, I have the following:

HTML Form (form.php)

<select name="list1" id="list1">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<select name="list2" id="list2">

</select>

JavaScript (within form.php)

<script type="text/javascript">
  $("#list1").change(function() {
    $("#list2").load("get_list2.php?id=" + $("#list1").val());
  });
</script>

get_list2.php

require_once("config.php");

$q1 = mysql_query("SELECT * FROM mytable WHERE id = '$_GET[id]'");
while($row1 = mysql_fetch_assoc($q1)){
  echo "<option>".$row1['item']."</option>";
}

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongye9182 dongye9182 2013-03-03 16:21

    Like other members have says, you should use PDO (with prepared statements) instead of mysql_.

    One possible implementation:

    HTML (form.php)

    <select name="list1" id="list1">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    
    <select name="list2" id="list2"></select>
    
    <script type="text/javascript">
    $("#list1").change(function() {
        $.ajax({
            url : "get_list2.php?id=" + $(this).val(),                          
            type: 'GET',                   
            dataType:'json',                   
            success : function(data) {  
                if (data.success) {
                    $('#list2').html(data.options);
                }
                else {
                    // Handle error
                }
            }
        });
    });
    </script>
    

    PHP (get_list2.php)

    require_once("config.php");
    
    $id = $_GET['id'];
    
    if (!isset($id) || !is_numeric($id))
        $reponse = array('success' => FALSE);
    else {
        // Where $db is a instance of PDO
    
        $query = $db->prepare("SELECT * FROM mytable WHERE id = :id");
        $query->execute(array(':id' => $id));
        $rows = $query->fetchAll(PDO::FETCH_ASSOC);
    
        $options = "";
        foreach ($rows as $row) {
            $options .= '<option value="'. $row .'">'. $row .'</option>';
        }
    
        $response = array(
            'success' => TRUE,
            'options' => $options
        );
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    

    PS : not tested but it should works... I guess.

    点赞 评论 复制链接分享

相关推荐