我有一个数据表,用户可以使用各种选项进行过滤。
我可以使用表单提交来处理数据,但表单接受$_POST
个变量,在某些情况下我希望用户只使用一个。
MP | Conservative | Year Elected
例如:
案例#1 - 用户搜索“保守派”派对,但并不关心当选的年份。
案例#2 - 用户搜索' 2005'选举年,但并不关心政党。
案例#3 - 用户搜索“对话”'派对和2005年'。
这是我的代码:
全局变量
if(empty($_POST['year_elec'])) {
$year = "show_all";
}
else {
$year = $_POST['year_elec'];
}
if(empty($_POST['party'])) {
$party = "show_all";
}
else {
$party = $_POST['party'];
}
主表生成:
if($year == "show_all" && $party == "show_all") {
$query = "SELECT * FROM mps";
}
else if(!empty($year) && $party ="show_all"){
$query = "SELECT * FROM mps WHERE year_elec = $year";
}
else if($year == "show_all" && !empty($party)) {
$query = "SELECT * FROM mps WHERE party = $party";
}
else {
$query = "SELECT * FROM mps WHERE year_elec = $year AND party = $party";
}
$res = mysqli_query($conn, $query);
while ($a = mysqli_fetch_assoc($res)) {
$name = $a['name'];
$party = $a['party'];
$consti = $a['cont'];
$year_elec = $a['year_elec'];
echo "<tr>";
echo "<td>" .$name. "</td>";
echo "<td>" .$party. "</td>";
echo "<td>" .$consti. "</td>";
echo "<td>" .$year_elec. "</td>";
echo "</tr>";
}
表格
<form method="post" action="mps.php">
<span class="css-select-moz">
<select name="year_elec" id="selectYear">
<option <?php if (isset($year) && $year=="2010") echo "selected";?> name="2010" value="2010">First elected 2010</option>
<option <?php if (isset($year) && $year=="2005") echo "selected";?> name="2005" value="2005">First elected 2005</option>
<option <?php if (isset($year) && $year=="2001") echo "selected";?> name="2001" value="2001">First elected 2001</option>
</select>
</span> <br />
<span class="css-select-moz">
<select name="party" id="selectParty">
<?php
$query = "SELECT DISTINCT party FROM mps";
$res = mysqli_query($conn, $query);
while($a = mysqli_fetch_assoc($res)) {
$party = $a['party'];
echo "<option name='$party' value='$party'>$party</option>";
}
?>
</select>
</span>
<input class="submit" type="submit" value="Load" />
</form>
答案 0 :(得分:0)
除了第一个=
中的一个else if
之外,我的代码中确实没有问题。
但是,您可以使用三元运算符进行操作,以便为$year
和$party
指定值。并且可以使用not equal运算符而不是not empty:
$year = $_POST['year_elec']?:'show_all';
$party = $_POST['party']?:'show_all';
if($year == "show_all" && $party == "show_all") {
$query = "SELECT * FROM mps";
}
else if($year != "show_all" && $party == "show_all"){
$query = "SELECT * FROM mps WHERE year_elec = $year";
}
else if($year == "show_all" && $party != "show_all") {
$query = "SELECT * FROM mps WHERE party = $party";
}
else {
$query = "SELECT * FROM mps WHERE year_elec = $year AND party = $party";
}
另请注意,您对SQL注入攻击持开放态度,理想情况下使用预准备语句和使用者可以选择的值列表(一系列政党和一系列日期)