[英]Filtering search results PHP
我試圖讓用戶能夠按升序或降序過濾搜索結果。 它不工作。
我認為這是我的 select 或 post 方法或其他東西的問題。
它不起作用的原因可能是什么?
<?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
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.