问题
I have been trying to look for a similar answer, however it seems I cannot find anything similar.
I have two tables in MySQL DB. User
and Team
. Each user is under a particular team.
The issue is that I want to populate two dropdowns' lists. The first dropdown should retrieve all teams available. The second dropdown should populate data according to which group the user selects in the first dropdown. Therefore if for example, user selects team A
, the second dropdown should populate users which are assigned under team A
.
$sql = "SELECT teamID FROM team";
$result = mysql_query($sql);
echo "<select name='team'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['teamID']."'>".$row['teamID']."</option>";
}
echo "</select>";
回答1:
echo "<select name='team' id='firstSelect'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['teamID'] ."'>" . $row['teamID'] ."
</option>";
}
echo "</select>";
echo '<div id="secondSelect">new form or select will go here</div>';
the Jquery
$('#firstSelect').on('change', function(){
var teamId= $(this).val();
$.post('yourPHPscript.php',
{
'teamId' : teamId
},
function (response, status) {
//response is the form or select generated from firstSelect
document.getElementById('secondSelect').value= response;
// or $('#secondSelect').html(response);
} ); // end post
}); // end function
In yourPHPscript.php take in the variable and echo the select (I suggest a form) that uses the firstSelect data. When it gets echoed it will show up in the second div. I hope I didn't make too many typos.
回答2:
You will need to do a few reconfigurations to suit your table data and output preferences, but this is a working method on my server/database...
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<?php
if(!$con=mysqli_connect("host","user","pass","db")){
echo "Failed to connect to MySQL: ",mysqli_connect_error();
}else{
$include_empty_teams_query="SELECT T.id AS `Tid`,T.name AS `Tname`,P.id AS `Pid`,P.name AS `Pname` FROM Teams T LEFT JOIN Players P ON T.id=P.teamid GROUP BY T.id,P.id HAVING P.id IS NOT NULL ORDER BY T.name,P.name;";
$exclude_empty_teams_query="SELECT T.id AS `Tid`,T.name AS `Tname`,P.id AS `Pid`,P.name AS `Pname` FROM Teams T LEFT JOIN Players P ON T.id=P.teamid GROUP BY T.id,P.id HAVING P.id IS NOT NULL ORDER BY T.name,P.name;";
if($result=mysqli_query($con,$include_empty_teams_query)){
if(mysqli_num_rows($result)){
$select1="<select name=\"team\"><option value=\"0\">All</option>";
$select2="<select name=\"player\"></select>";
$last_team=NULL;
while($row=mysqli_fetch_assoc($result)){
$data[]=$row;
if($row["Tname"]!=$last_team){
if($row["Pid"]===NULL){
$select1.="<option disabled>{$row["Tname"]}</option>";
}else{
$select1.="<option value=\"{$row["Tid"]}\">{$row["Tname"]}</option>";
}
}
$last_team=$row["Tname"];
}
$select1.="</select>";
echo $select1," ",$select2;
mysqli_free_result($result);
}else{
echo "Query Logic Error";
}
}else{
echo "Query Syntax Error: ",mysqli_error($con);
}
}
?>
</body>
<script>
var json=<?=json_encode($data)?>; // cache for future referencing
$('[name="team"]').on('change',function(e){
var selVal=$(this).find(":selected").val();
if($(this).val()!=0){ // filter json
var newOptions=$(json).filter(function(i,sub){return sub.Tid==selVal});
}else{
var newOptions=json;
}
var $select2=$('[name="player"]');
$select2.empty(); // remove old options
$.each(newOptions,function(i,sub){
$select2.append($("<option></option>").attr("value",sub.Pid).text(sub.Pname));
});
}).change(); // trigger change() onload
</script>
</html>
Rendered Outputs ([default/onload] and [Pearl Jam selected]):
and
Output Sourcecode:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<select name="team"><option value="0">All</option><option value="2">49'ers</option><option value="3">Pearl Jam</option><option value="5">Trump</option><option value="1">Yankees</option></select> <select name="player"></select></body>
<script>
var json=[{"Tid":"2","Tname":"49'ers","Pid":"4","Pname":"Jerry Rice"},{"Tid":"2","Tname":"49'ers","Pid":"3","Pname":"Joe Montana"},{"Tid":"3","Tname":"Pearl Jam","Pid":"5","Pname":"Eddie Vedder"},{"Tid":"3","Tname":"Pearl Jam","Pid":"6","Pname":"Jeff Ament"},{"Tid":"3","Tname":"Pearl Jam","Pid":"9","Pname":"Matt Cameron"},{"Tid":"3","Tname":"Pearl Jam","Pid":"8","Pname":"Mike McCready"},{"Tid":"3","Tname":"Pearl Jam","Pid":"7","Pname":"Stone Gossard"},{"Tid":"5","Tname":"Trump","Pid":"10","Pname":"Donald Trump"},{"Tid":"1","Tname":"Yankees","Pid":"2","Pname":"Babe Ruth"},{"Tid":"1","Tname":"Yankees","Pid":"1","Pname":"Mickey Mantle"}]; // cache for future referencing
$('[name="team"]').on('change',function(e){
var selVal=$(this).find(":selected").val();
if($(this).val()!=0){ // filter json
var newOptions=$(json).filter(function(i,sub){return sub.Tid==selVal});
}else{
var newOptions=json;
}
var $select2=$('[name="player"]');
$select2.empty(); // remove old options
$.each(newOptions,function(i,sub){
$select2.append($("<option></option>").attr("value",sub.Pid).text(sub.Pname));
});
}).change();
</script>
</html>
The advantages of my code are:
- There are no ajax calls. This means that there is no unnecessary server load from multiple team changes from the user. The database is queried once, and all data is stored in a javascript variable.
- I have removed the old
mysql_
functions, and implementedmysqli_
functions to modernize your process. - I have declared two separate queries, but only use one in my post. This allows you to decide whether or not you wish to include teams in your first dropdown that have are player-less.
- I use
mysqli_fetch_assoc()
instead ofmysqli_fetch_array()
because I do not use the numeric keys that it provides. - If you include player-less teams, the team name will be displayed but with a
disabled
attribute so that it cannot be selected -- this is deliberate UX feature. - I use
<?=
and?>
as shorthand for echo this php value around thejson_encode()
on$data
. - I use
.change()
at the end of my jquery onchange function, so that the function is triggered on page load.
Database Tables Used:
CREATE TABLE `Teams` (
`id` int(10) NOT NULL,
`name` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `Teams` (`id`, `name`) VALUES
(1, 'Yankees'),
(2, '49\'ers'),
(3, 'Pearl Jam'),
(4, 'Empty Team'),
(5, 'Trump');
ALTER TABLE `Teams`
ADD PRIMARY KEY (`id`);
ALTER TABLE `Teams`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
CREATE TABLE `Players` (
`id` int(10) NOT NULL,
`name` varchar(100) NOT NULL,
`teamid` int(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `Players` (`id`, `name`, `teamid`) VALUES
(1, 'Mickey Mantle', 1),
(2, 'Babe Ruth', 1),
(3, 'Joe Montana', 2),
(4, 'Jerry Rice', 2),
(5, 'Eddie Vedder', 3),
(6, 'Jeff Ament', 3),
(7, 'Stone Gossard', 3),
(8, 'Mike McCready', 3),
(9, 'Matt Cameron', 3),
(10, 'Donald Trump', 5);
ALTER TABLE `Players`
ADD PRIMARY KEY (`id`);
ALTER TABLE `Players`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
来源:https://stackoverflow.com/questions/43557706/use-db-results-to-populate-1st-dropmenu-and-1st-dropmenu-value-to-populate-2nd