我正在创建一个网站,并且需要一些有关如何创建类似内容的帮助:
https://matchstat.com/tennis/head-to-head
(用户基本上可以选择任意2名玩家并比较他们的胜利)。
但是,我不是在搜索框中输入,而是使用下拉框,有关如何实现这一点的任何想法?
到目前为止,我已经设置了我的数据库并使用SQL,PHP连接。
快速说明我的表格:
[select player] //这将是一个下拉/选项框
Forename://这些字段的内容取决于用户从上面的下拉/选项框中选择的播放器 姓: 国籍: 出生日期: 高度: 重量:
任何建议都将受到赞赏。
非常感谢
答案 0 :(得分:1)
如果您的SQL查询结果存储了一个二维数组(行x列),您只需循环遍历数组的结果即可打印<option>
的下拉列表<select>
像这样的盒子:
<?php
$users = // SQL query result
echo "<select>";
foreach($users as $user) {
$data = $user["forename"];
echo "<option value='$data'>$data</option>";
}
echo "</select>";
?>
根据要求,这是一个更复杂的解决方案,可以创建一个下拉框,允许显示数据。这也使用jQuery(也可以使用普通JS,但jQuery简化了很多):
<select id="dropdown">
<?php
// this PHP is essentially the same as in the above example
$users = [ // this is the test array I used. The SQL result should be in the same format for this to work.
[
"forename"=>"a_name",
"dob"=>"never",
"height"=>"too_tall",
"weight"=>"too_heavy",
"nationality"=>"martian"
],
[
"forename"=>"second_name",
"dob"=>"always",
"height"=>"too_short",
"weight"=>"too_light",
"nationality"=>"moon"
],
[
"forename"=>"third_name",
"dob"=>"forever",
"height"=>"300ft",
"weight"=>"2000lb",
"nationality"=>"Earth"
]
];
$userDataArray = []; // multidimensional array
$user_id = 0;
foreach($users as $user) {
$data = $user["forename"];
echo "<option value='$user_id'>$data</option>";
$user_id++;
$userDataArray[] = [ "forename"=>$user["forename"], "dob"=>$user["dob"], "height"=>$user["height"], "weight"=>$user["weight"], "nationality"=>$user["nationality"] ];
// index 0 = forename, 1 = DOB, 2 = height, 3 = weight, 4 = nationality
}
?>
</select><br />
<span id="display"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><!-- load jQuery library -->
<script>
var users = [
<?php // translate PHP array to JS one
foreach($userDataArray as $user) {
echo "{ forename: '" . $user["forename"] . "', dob: '" . $user["dob"] . "', weight: '" . $user["weight"] . "', height: '" . $user["height"] . "', nationality: '" . $user["nationality"] . "'},";
}
?>
];
$("#dropdown").change(function() {
var i = $("#dropdown").val();
$("#display").html("Name: " + users[i].forename + "<br />DOB: " + users[i].dob + "<br />Weight: " + users[i].weight + "<br />Height: " + users[i].height + "<br />Nationality: " + users[i].nationality);
});
</script>
对不起,这个答案太长而且令人困惑。我不确定是否有更简单的方法,特别是在处理两种不同的语言时(是的,你需要处理服务器(使用PHP的数据库)和客户端(使用JS下拉)。我希望这样帮助!
请参阅Ideone的the now correct output here。