过滤搜索结果 PHP



我试图让用户能够按升序或降序过滤搜索结果。 它不起作用。

我认为这是我的选择或发布方法或其他问题。

它不起作用的原因可能是什么?

<?php
$search = "";
if(isset($_POST["search"])){
$search = $_POST["search"];
$Ascending= $_POST["Sort By"];
$Descending= $_POST["Sort By"];
}
?>
<form method="POST">
<input type="text" name="search" placeholder="Search for Question"
value="<?php echo $search;?>"/>
<label for="Sort">SortBy:</label>
<select id="SortBy" name="Sort By">
<option value="Ascending">Ascending Order</option>
<option value="Descending">Descending Order</option>
<input type="submit"
</select>
</form>
<?php
if(isset($Ascending)) {
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/SearchTableASC.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
if(isset($Descending)){
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/DescendingOrder.sql.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
?>
<!--This part will introduce us to PHP templating,
note the structure and the ":" -->
<!-- note how we must close each check we're doing as well-->
<?php if(isset($results) && count($results) > 0):?>
<p>This shows when we have results</p>
<ul>
<!-- Here we'll loop over all our results and reuse a specific template for each iteration,
we're also using our helper function to safely return a value based on our key/column name.-->
<?php foreach($results as $row):?>
<li>
<?php echo get($row, "question")?>
<a href="delete.php?QuestionId=<?php echo get($row, "id");?>">Delete</a>
</li>
<?php endforeach;?>
</ul>
<?php else:?>
<p>This shows when we don't have results</p>
<?php endif;?>

您没有正确使用传入的参数:

$Ascending= $_POST["Sort By"]; 
$Descending= $_POST["Sort By"];

在这里,您将升序和降序设置为相同的值。

你应该做这样的事情:

$ascOrDec = $_POST['Sort By'];

然后在选择查询之前检查$ascOrDec的值。

最新更新