Using PHP & MySQL to populate dropdown

心不动则不痛 提交于 2019-12-01 14:33:52

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!