gpt4 book ai didi

php - 在 PHP 中通过多个表单字段提交操作 HTML 表数据

转载 作者:行者123 更新时间:2023-11-30 00:10:21 25 4
gpt4 key购买 nike

我有一个数据表,用户可以使用各种选项进行过滤。

我可以通过表单提交来操作数据,但表单接受两个 $_POST 变量,并且在某些情况下我希望用户只使用一个。

MP |保守 |当选年份

例如:

案例 #1 - 用户搜索“保守党”,但不关心当选年份。

案例#2 - 用户搜索“2005”选举年,但不关心政党。

案例 #3 - 用户搜索“Conversative”政党和“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>

最佳答案

除了第一个 else if 中的单个 = 之外,我确实没有发现您的代码有问题。

但是,您可以使用三元运算符来整理内容,以将值分配给 $year$party。并且可以使用不等于运算符来代替非空:

$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 注入(inject)攻击,最好使用准备好的语句和用户可以从中选择的值白名单(政党数组和日期数组)

关于php - 在 PHP 中通过多个表单字段提交操作 HTML 表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com