我正在一个需要用户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语句。任何帮助是极大的赞赏。

最佳答案

因此,您要允许至少填写一个字段?

我可以想到的一种方法是将所有值放入关联数组中,并循环遍历该数组,然后检查该字段是否为空。

例:

// 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())语句。

关于php - 使用用户输入过滤查询的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35830113/

10-11 22:09
查看更多