[英]How to fetch data from MySQL database to Select drop-down list?
I am trying to populate a select list from a MySQL database after I have selected an autocomplete suggestion from jQuery autocomplete. 从jQuery自动完成功能中选择了自动完成功能建议后,我试图从MySQL数据库中填充选择列表。
For example, if i click on one of the autocomplete suggestions like 10 - computer
in the first text box (see my sample data below), I want to fetch the corresponding names ( sahil
, sumit
, anil
, shweta
), and add them to the select in second text box. 例如,如果我在第一个文本框中单击自动完成建议之一(例如10 - computer
(请参阅下面的示例数据), sahil
获取相应的名称( sahil
, sumit
, anil
, shweta
),并将其添加到在第二个文本框中选择。
If instead I click 12-History
I want to fetch those corresponding names ( sanchita
, riya
, neha
, pratik
. 相反,如果我点击12-History
我想获取这些相应的名称( sanchita
, riya
, neha
, pratik
。
How to achieve this? 如何实现呢? Any help would be appreciated. 任何帮助,将不胜感激。
table structure: 表结构:
--
-- 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');
SearchForm.php SearchForm.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>
search.php search.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);
?>
names.php names.php
<?php
require_once 'conn.php';
$names = $_GET['term'];
$names = array();
$names = $conn->real_escape_string($names);
$stmt = $conn->query("SELECT Student_Name FROM `stndb` WHERE
Div_No='$names'");
$rows = $stmt->num_rows;
if($rows > 0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['Student_Name'];
}
}
echo json_encode($names);
?>
FIRSTLY as has been pointed out in the comments your code is open to SQL injection and you should IMMEDIATELY CHANGE THAT . 首先,如注释中所指出的,您的代码可以进行SQL注入,因此您应该立即进行更改 。 Update your search.php
to use PDO and prepared statements , there are many guides and tutorials online. 更新您的search.php
以使用PDO和准备好的语句 ,在线上有许多指南和教程。
Once you have done that, seriously, don't proceed until you've fixed that - 认真完成之后,请务必先解决,然后再继续操作 -
As I understand it, you want to use autocomplete in the first #search
input to display the Div_no
and Div_name
values. 据我了解,您想在第一个#search
输入中使用自动完成功能来显示Div_no
和Div_name
值。 Once the user selects one of those values, a second select field will load the Student_Name
s of the selected Div_no
. 一旦这些值的用户选择一个,第二选择字段将加载Student_Name
选定第Div_no
。
Your existing code already does the first part. 您现有的代码已经完成了第一部分。 You need to update it to something when the user selects a value - jQuery autocomplete has a select event for that. 当用户选择一个值时,您需要将其更新为某种内容-jQuery自动完成功能为此具有一个select事件 。
And to load the set of students, you will need to fire of an AJAX request when that select event is triggered. 为了加载一组学生,您将需要在触发该选择事件时触发AJAX请求 。 You will have to prepare a new PHP file, something like search BUT USING PDO , let's say you call it names.php
. 您将需要准备一个新的PHP文件,例如使用PDO搜索names.php
。 It will receive the selected Div_no
as a GET parameter, and should query your database to find the students. 它将接收选定的Div_no
作为GET参数,并应查询数据库以查找学生。 The query would be something like: 该查询将类似于:
SELECT Student_Name FROM stndb WHERE Div_No = ?
And just like in search.php
, you will iterate over the results, generating an array of names: 就像在search.php
,您将遍历结果,生成一个名称数组:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['Student_Name'];
}
And it should return the results as JSON, easy to work with in Javascript: 并且它应该以JSON形式返回结果,易于在Javascript中使用:
echo json_encode($names);
So, first your HTML: 因此,首先您的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>
Now your Javascript: 现在您的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);
}
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.