如何从MySQL数据库获取数据到“选择”下拉列表?

时间:2019-09-12 08:48:10

标签: javascript php jquery mysql jquery-ui-autocomplete

从jQuery自动完成中选择自动完成建议后,我试图从MySQL数据库中填充选择列表。

例如,如果我在第一个文本框中单击诸如10 - computer之类的自动完成建议(请参见下面的示例数据),我想获取相应的名称(sahil,{{ 1}},sumitanil),并将它们添加到第二个文本框中的选择中。

相反,如果我单击shweta,我想获取那些对应的名称(12-Historysanchitariyaneha

如何实现?任何帮助将不胜感激。

表结构:

pratik

SearchForm.php

--
-- Table structure for table `stndb`
--

DROP TABLE IF EXISTS `stndb`;
CREATE TABLE IF NOT EXISTS `stndb` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Div_No` int(2) DEFAULT NULL,
  `Div_Name` varchar(30) DEFAULT NULL,
  `Student_Name` varchar(30) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `stndb`
--

INSERT INTO `stndb` (`id`, `Div_No`, `Div_Name`, `Student_Name`) VALUES
(1, 10, 'computer', 'sahil'),
(2, 10, 'computer', 'sumit'),
(3, 10, 'computer', 'anil'),
(4, 10, 'computer', 'shweta'),
(5, 11, 'IT', 'apoorva'),
(6, 11, 'IT', 'neeta'),
(7, 11, 'IT', 'sachin'),
(8, 11, 'IT', 'priya'),
(9, 12, 'History', 'sanchita'),
(10, 12, 'History', 'riya'),
(11, 12, 'History', 'neha'),
(12, 12, 'History', 'pratik');

search.php

<html>
    <head>
    <title> Search Record </title> 
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/jquery-ui.css"/>
    </head>
    <body>
    <form action="" method ="POST" accept-charset="UTF-8" role="form" >
        <fieldset>
        <div class="form-group">
            <input class="form-control" id="search" name="DivNumber" type="text" placeholder="Enter Division Number"  type="text" required>
        </div>

        <div class="form-group">
            <select input class="form-control" id= "nameList" name="StName" type="text" placeholder="Select Student"  type="text" readonly="readonly">
                <option value="one">Sahil</option>
                <option selected value="two">Sumit</option>
                <option value="three">Anil</option>
                <option value="four">Shweta</option>
            </select>
        </div>
        <input class="btn btn-lg btn-info btn-block" type="submit" value="Search  ">
        </fieldset>
    </form>

<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    $("#search").autocomplete({
        source: 'search.php',
        minLength: 1,
    });
});
</script>

</body>
</html>

names.php

<?php
require_once 'conn.php';

$search = $_GET['term'];

$list = array();

$search = $conn->real_escape_string($search);   

$query = $conn->query("SELECT DISTINCT Div_No, Div_Name FROM `stndb` WHERE Div_No LIKE '$search%' OR Div_Name LIKE '$search%' LIMIT 10") or die(mysqli_connect_errno());

$rows = $query->num_rows;

if($rows > 0){
    while($fetch = $query->fetch_assoc()){

        $data['value'] = $fetch['Div_No'];
        $data['label'] = $fetch['Div_No']. "-". $fetch['Div_Name']."";  
        array_push($list, $data);
    }
}

echo json_encode($list);
?>

1 个答案:

答案 0 :(得分:1)

首先已在注释中指出,您的代码可以进行SQL注入,因此您应该立即进行更改。将您的search.php更新为use PDO and prepared statements,在线上有很多指南和教程。

完成此操作后,请认真解决,除非您已解决-

据我了解,您想在第一个#search输入中使用自动完成功能来显示Div_noDiv_name值。用户选择了其中一个值后,第二个选择字段将加载所选Student_Name中的Div_no个。

您现有的代码已经完成了第一部分。当用户选择一个值-jQuery autocomplete has a select event时,您需要将其更新为某些内容。

要加载一组学生,您将需要在触发该选择事件时触发an AJAX request。您将必须准备一个新的PHP文件,例如搜索但要使用PDO ,假设您将其命名为names.php。它将接收选定的Div_no作为GET参数,并应查询数据库以查找学生。该查询将类似于:

SELECT Student_Name FROM stndb WHERE Div_No = ?

就像在search.php中一样,您将遍历结果,生成一个名称数组:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $names[] = $row['Student_Name'];
}

它应该以JSON格式返回结果,易于在Javascript中使用

echo json_encode($names);

因此,首先您的HTML:

<form action="" method ="POST" accept-charset="UTF-8" role="form" >
    <fieldset>
        <div class="form-group">
            <input class="form-control" id="search" name="DivNumber" type="text" placeholder="Enter Division Number"  type="text" required>
        </div>
        <div class="form-group">
            <select input class="form-control" id="nameList" name="StName" type="text" placeholder="Select Student" type="text" readonly="readonly">
        </div>
        <input class="btn btn-lg btn-info btn-block" type="submit" value="Search  ">
    </fieldset>
</form>

现在使用Javascript

$( "#search").autocomplete({
    source: 'search.php',
    minLength: 1,
    // Here is the select event handler, fired when someone selects something
    select: function(event, ui) { 

        // Here is an AJAX request to load the right set of students
        $.ajax({
            url: 'names.php', // This is your new PHP file which returns the names
            data: {
                div_no: ui.item.value // This is the selected Div_No
            },
            dataType: 'json',
            success: function(response) { // This is what happens when the AJAX 
                                          // call succeeds and returns the names
                var output = '';

                // Iterate over the data and build a list of options
                for (var i in response) {
                    output += '<option value="">' + response[i] + '</option>';
                }

                // Update our select with the options we just built
                $('#nameList').html(output);
            }
        });
    }
});