我正在开发一个项目,该项目需要用户的4个字段来过滤来自mysql数据库的查询。
用户输入日期范围,名称搜索和/或游戏结果。查询可以在未填写所有字段时起作用,并且必须在填写所有字段时起作用。
我需要编写一个完成所有这一切的程序,但我能想到的唯一方法就是编写一堆if语句来查看用户是否已填写或未填写每个单独的表单元素。必须有更好,更有效的方法来做到这一点。
<form method="post" action="extra.php">
Date Range From:
<input type="text" id="dateFrom" name="dateFrom" value=""/>
To:
<input type="text" id="dateTo" name="dateTo" value=""/>
<br/>
Name Search:
<input type="text" id="nameSearch" name="nameSearch" value=""/>
<br/>
Game Result:
<select name="gameResult">
<option value="any">Any</option>
<option value="p1">Player 1</option>
<option value="p2">Player 2</option>
<option value="draw">Draw</option>
</select>
<input type="submit" id="submit">
</form>
<?php
include('../inclass/db_connect.php');
if(isset($_POST['dateFrom']) && ($_POST['dateTo']) && ($_POST['nameSearch']) && ($_POST['gameResult'])){
$dateFrom = $_POST['dateFrom'];
$dateTo = $_POST['dateTo'];
$nameSearch = $_POST['nameSearch'];
$gameResult = $_POST['gameResult'];
$result =$pdo->prepare("SELECT matchDate, player1, player2, result, eco FROM matches WHERE (matchDate BETWEEN '$dateFrom' AND '$dateTo') AND (player1 LIKE '$nameSearch%') OR (player2 LIKE '$nameSearch%') AND (result ='1') ORDER BY matchDate desc LIMIT 250");
$result->execute();
?>
<table border="1">
<tr>
<th>Match Date</th>
<th>Player 1</th>
<th>Player 2</th>
<th>Result</th>
<th>ECO Code</th>
<th>Match Details</th>
</tr>
<?php
for($i=0; $row = $result->fetch(); $i++){
?>
<tr>
<td><?php echo $row['matchDate']; ?></td>
<td><?php echo $row['player1']; ?></td>
<td><?php echo $row['player2']; ?></td>
<td><?php echo $row['result']; ?></td>
<td><?php echo $row['eco']; ?></td>
<td><a href="details.php" id=".$row['id'].">Details</a></td>
</tr>
<?php
}
?>
</table>
<?php
}
http://cps276.net/zgambrell/04/extra.php
我只需要在正确的方向上获得一些指导,如何完成此操作而无需编写50 if语句。任何帮助是极大的赞赏。
答案 0 :(得分:0)
所以你想要允许填写至少一个字段?
我能想到的一种方法是将所有值放入一个关联数组并循环遍历它并检查该字段是否为空。
示例:
// put all of the values into an array
$searchForm = [
'dateFrom' = $_POST['dateFrom'],
'dateTo' = $_POST['dateTo'],
'nameSearc' = $_POST['nameSearch'],
'gameResult' = $_POST['gameResult'],
];
// loop through the array and see if the fields are not empty
foreach($searchForm as $inputField) {
// if the fieldsa re not empty
if(!empty($inputField))
{
// put them into a new array
$searchValues = $inputField
}
}
// check the number of elements of the array
if(count($searchValues) === 0) {
// return back to the page and show an error that at least one field is required.
}
// execute the query here
您可以将此代码放入函数中,并重复使用它来验证其他表单字段。只需将输入字段数组作为参数传递即可。
我不知道这是否可行,但它应该让你知道如何减少if(isset())语句。