如何正确应用动态生成的PHP / MySQL搜索过滤器?

问题描述 投票:-4回答:2

我已经创建了搜索工具(https://brawlins.com/soarOpen/search.php?term=),并且可以使用搜索功能。我希望用户能够通过从下拉菜单中选择一个选项并能够从多个过滤器中选择选项来过滤搜索。我有五个不同的选项供用户筛选他们的搜索,这些选项中填充了来自数据库的正确信息。搜索时,过滤器的下拉列表也会更新。但是,一旦我从下拉菜单之一中选择一个选项,结果就不会更新。从下拉菜单中选择选项后,如何更新结果?这是带有三个下拉菜单的filter.php页面的代码:

<?php

$soar_search_results = array();  
$searchTerm = "'%".$term."%'";
$searchTermTwo = "'%".$term."%')";
$soar_search_results[] = '(title LIKE '.$searchTerm.' OR subject LIKE '.$searchTerm.' OR source LIKE '.$searchTerm.' OR license LIKE '.$searchTerm.' OR author LIKE '.$searchTerm.' OR e_isbn_number LIKE '.$searchTerm.' OR isbn_number LIKE '.$searchTermTwo;


$soar_array = array();
if ($type_search != ""){
    $filter_type = "&type=$type_search";
    $soar_array[] = "type = '$type_search'";
}

if ($subject_search != ""){
    $filter_subject = "&subject=$subject_search";
    $soar_array[] = "subject = '$subject_search'";
} 

if ($source_search != ""){
    $filter_source = "&source=$source_search";
    $soar_array[] = "source = '$source_search'"; 
} 

if ($license_search != ""){
    $filter_license = "&usage=$license_search";
    $soar_array[] = "license = '$license_search'";
}

if ($review_search != ""){
    $filter_review = "&review=$review_search";
    $soar_array[] = "review = '$review_search'";
}

if ($isbn_search != ""){
    $soar_array[] = "isbn_number = '$isbn_search'";
} 

$soarSearch = implode(" AND ", $soar_array);
$soarResults = implode(" AND ", $soar_search_results);

if ((!empty($soar_array)) && ($term != "")){
    $combine = " AND ";
}
?>
<div class="filterContainer">
<div class="filterContent">
<div class="container">

<?php
//START OF TYPE FILTER 
if ($term != ""){
    $type_query = $conn->prepare("SELECT type, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . $combine . $soarResults . " GROUP BY type ORDER BY COUNT(type) DESC");
    $type_query->execute();
} 
if ($term == "" && $soarSearch != "") {
    $type_query = $conn->prepare("SELECT type, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . " GROUP BY type ORDER BY COUNT(type) DESC");
    $type_query->execute();
}
if ($term == "" && $soarSearch == "") {
    $type_query = $conn->prepare("SELECT type, COUNT(*) as total FROM oer_search GROUP BY type ORDER BY COUNT(type) DESC");
    $type_query->execute();
}

echo "<div class='filter'>";
echo "<h4 class='filterTitle'>Material Types:</h4>";
?>
<div class="dropdown">
    <button class="btn btn-filter dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select - Material Type
    </button>
    <div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton2'>
    <?php
        while($row = $type_query->fetch(PDO::FETCH_ASSOC)) {
            $type_name = $row['type'];
            $total_type = number_format($row['total']);
            $all = urlencode($term) . $filter_license . $filter_subject . $filter_review . $filter_source;

            echo "<a class='dropdown-item' href='search.php?term=$all&type=$type_name'>$type_name ($total_type)</a>";
        }

    echo "</div>";
echo "</div>";//end of dropdown
echo "</div>";//end of filter
//END OF TYPE FILTER

//START OF SOURCE FILTER 
if ($term != ""){
    $source_query = $conn->prepare("SELECT source, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . $combine . $soarResults . " GROUP BY source ORDER BY COUNT(source) DESC");
    $source_query->execute();
} 
if ($term == "" && $soarSearch != ""){
    $source_query = $conn->prepare("SELECT source, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . " GROUP BY source ORDER BY COUNT(source) DESC");
    $source_query->execute();
} 
if ($term == "" && $soarSearch == "") {
    $source_query = $conn->prepare("SELECT source, COUNT(*) as total FROM oer_search GROUP BY source ORDER BY COUNT(source) DESC");
    $source_query->execute();
}

echo "<div class='filter'>";
echo "<h4 class='filterTitle'>Sources:</h4>";
?>
<div class="dropdown">
    <button class="btn btn-filter dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select - Source
    </button>
    <div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton2'>
    <?php
        while($row = $source_query->fetch(PDO::FETCH_ASSOC)) {
            $source_name = $row['source'];
            $total_source = number_format($row['total']);
            $all = urlencode($term) . $filter_license . $filter_subject . $filter_review . $filter_type;

            echo "<a class='dropdown-item' href='search.php?term=$all&source=$source_name'>$source_name ($total_source)</a>";
        }

    echo "</div>";
echo "</div>";//end of dropdown
echo "</div>";//end of filter
//END OF SOURCE FILTER

//START OF SUBJECT FILTER 
if ($term != ""){
    $subject_query = $conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . $combine . $soarResults . " GROUP BY subject ORDER BY COUNT(subject) DESC");
    $subject_query->execute();
} 
if ($term == "" && $soarSearch != ""){
    $subject_query = $conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . " GROUP BY subject ORDER BY COUNT(subject) DESC");
    $subject_query->execute();
} 
if ($term == "" && $soarSearch == "") {
    $subject_query = $conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search GROUP BY subject ORDER BY COUNT(subject) DESC");
    $subject_query->execute();
}

echo "<div class='filter'>";
echo "<h4 class='filterTitle'>Subjects:</h4>";
?>
<div class="dropdown">
    <button class="btn btn-filter dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select - Subject
    </button>
    <div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton2'>
    <?php
        while($row = $subject_query->fetch(PDO::FETCH_ASSOC)) {
            $subject_name = $row['subject'];
            $subject_link = urlencode($subject_name);
            $total_subject = number_format($row['total']);
            $all = urlencode($term) . $filter_license . $filter_source . $filter_review . $filter_type;
            if($subject_name != ""){
                echo "<a class='dropdown-item' href='search.php?term=$all&subject=$subject_link'>$subject_name ($total_subject)</a>";
            }
        }

    echo "</div>";
echo "</div>";//end of dropdown
echo "</div>";//end of filter
//END OF SUBJECT FILTER

//START OF LICENSE FILTER 
if ($term != ""){
    $license_query = $conn->prepare("SELECT license, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . $combine . $soarResults . " GROUP BY license ORDER BY COUNT(license) DESC");
    $license_query->execute();
} 
if ($term == "" && $soarSearch != ""){
    $license_query = $conn->prepare("SELECT license, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . " GROUP BY license ORDER BY COUNT(license) DESC");
    $license_query->execute();
} 
if ($term == "" && $soarSearch == "") {
    $license_query = $conn->prepare("SELECT license, COUNT(*) as total FROM oer_search GROUP BY license ORDER BY COUNT(license) DESC");
    $license_query->execute();
}

echo "<div class='filter'>";
echo "<h4 class='filterTitle'>Usage Rights:</h4>";
?>
<div class="dropdown">
    <button class="btn btn-filter dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select - Usage Right
    </button>
    <div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton2'>
    <?php
        while($row = $license_query->fetch(PDO::FETCH_ASSOC)) {
            $license_name = $row['license'];
            $total_license = number_format($row['total']);
            $all = urlencode($term) . $filter_subject . $filter_source . $filter_review . $filter_type;
            if($license_name != ""){
                echo "<a class='dropdown-item' href='search.php?term=$all&usage=$license_name'>$license_name ($total_license)</a>";
            }
        }

    echo "</div>";
echo "</div>";//end of dropdown
echo "</div>";//end of filter
//END OF LICENSE FILTER

//START OF REVIEWED FILTER 
if ($term != ""){
    $review_query = $conn->prepare("SELECT review, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . $combine . $soarResults . " GROUP BY review ORDER BY COUNT(review) DESC");
    $review_query->execute();
} 
if ($term == "" && $soarSearch != ""){
    $review_query = $conn->prepare("SELECT review, COUNT(*) as total FROM oer_search WHERE " . $soarSearch . " GROUP BY review ORDER BY COUNT(review) DESC");
    $review_query->execute();
} 
if ($term == "" && $soarSearch == "") {
    $review_query = $conn->prepare("SELECT review, COUNT(*) as total FROM oer_search GROUP BY review ORDER BY COUNT(review) DESC");
    $review_query->execute();
}

echo "<div class='filter'>";
echo "<h4 class='filterTitle'>Reviewed Resources:</h4>";
?>
<div class="dropdown">
    <button class="btn btn-filter dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select - Reviewed
    </button>
    <div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton2'>
    <?php
        while($row = $review_query->fetch(PDO::FETCH_ASSOC)) {
            $review_name = $row['review'];
            $total_review = number_format($row['total']);
            $all = urlencode($term) . $filter_subject . $filter_source . $filter_license . $filter_type;
            if($review_name != ""){
                echo "<a class='dropdown-item' href='search.php?term=$all&usage=$review_name'>$review_name ($total_review)</a>";
            }
        }

    echo "</div>";
echo "</div>";//end of dropdown
echo "</div>";//end of filter
//END OF REVIEWED FILTER

//RESET FILTERS BUTTON
echo "<div class='filter'>";
if ($type_search != "" or $subject_search != "" or $source_search != "" or $license_search != "" or $review_search != ""){
    echo "<a class='btn btn-filter-clear' href='search.php?term=$term' role='button'><strong>Clear Filters <i class='far fa-times-circle'></i></strong></a>";
}
echo "</div>";
?> 
</div>
</div>
</div>

我已经为搜索结果创建了class。这是该文件的代码:

<?php
class resultsProvider {

    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }

    public function getNumResults ($term) {

        $query = $this->conn->prepare("SELECT COUNT(*) as total
                FROM oer_search WHERE title LIKE :term
                OR type LIKE :term
                OR subject LIKE :term
                OR source LIKE :term
                OR author LIKE :term
                OR license LIKE :term
                OR isbn_number LIKE :term
                OR e_isbn_number LIKE :term");

        $searchTerm = "%". $term . "%";
        $query->bindParam(":term", $searchTerm);
        $query->execute();

        $row = $query->fetch(PDO::FETCH_ASSOC);
        return $row["total"];
    }

    public function getResultsHTML($page, $pageSize, $term) {

        $fromLimit = ($page - 1) * $pageSize;

        $query = $this->conn->prepare("SELECT *
                FROM oer_search WHERE title LIKE :term
                OR type LIKE :term
                OR subject LIKE :term
                OR source LIKE :term
                OR author LIKE :term
                OR license LIKE :term
                OR isbn_number LIKE :term
                OR e_isbn_number LIKE :term
                LIMIT :fromLimit, :pageSize");


        $searchTerm = "%". $term . "%";
        $query->bindParam(":term", $searchTerm);
        $query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
        $query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
        $query->execute();


            while($row = $query->fetch(PDO::FETCH_ASSOC)) {

                $id = $row['id'];
                $type = $row['type'];
                $link = $row['link'];
                $title = $row['title'];
                $description = $row['description'];
                $pub_date = $row["publication_date"];
                $source = $row['source'];
                $isbn = $row["isbn_number"];
                $e_isbn = $row["e_isbn_number"];
                $license = $row['license'];
                $license_url = $row['license_url'];
                $base_url = $row['base_url'];
                $author = $row['author'];
                $review = $row['review'];
                $image = $row["image_url"];
                $loc_collection = $row["loc_collection"];

                $resultsHTML .= "<div class='row'>";
                $resultsHTML .= "<div class='col-md-2'>";
                    $resultsHTML .= "<a class='result' href='$link'><img src='images/icons/$type.png' class='type-icon' alt='$type icon'/></a>"; 
                $resultsHTML .= "</div>";//end of column

                $resultsHTML .= "<div class='col-md-8'>";
                    switch ($review) {
                        case "Reviewed Resource":
                            $resultsHTML .=  "<span class='title'><strong><a rel='external' href='$link'>$title</a></strong></span> <img data-toggle='tooltip' data-placement='right' title='Reviewed Resouce' class='review-icon' src='images/star.png' alt='star icon'><br>";
                            break;
                        default:
                            $resultsHTML .= "<h5 class='title'><a class='result' href='$link' data-linkId='$id'>$title</a></h5>";
                            break;   
                    }

                    if($author != "" && $type != "Image") {
                        $resultsHTML .= "<span class='author'><strong>Author:</strong> $author</span><br>";
                    }
                    if($author != "" && $type == "Image") {
                        $resultsHTML .= "<span class='author'><strong>Artist:</strong> $author</span><br>";
                    }

                    $resultsHTML .= "<span class='type'><strong>Type:</strong> $type</span><br>";

                    switch ($source) {
                        case "Library of Congress":
                            $resultsHTML .= "<span class='source'><strong>Source:</strong> <a href='$base_url'>$source</a></span><br>";
                            $resultsHTML .= "<span class='loc_coll'><strong>Collection</strong>: <a href='$base_url' rel='external'>$loc_collection</a></span><br/>";
                            break;
                        default:
                            $resultsHTML .= "<span class='source'><strong>Source:</strong> <a href='$base_url'>$source</a></span><br>";
                            break;
                    }

                    switch ($license) {
                        case "All Rights Reserved":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#allrights'> $license</a></span><br>";
                            break;
                        case "ANU Press":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#anu'> $license</a></span><br>";
                            break;
                        case "Attribution":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by'> $license</a></span><br>";
                            break;
                        case "Attribution-NoDerivs":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by-nd'> $license</a></span><br>";
                            break;
                        case "Attribution-NonCommercial":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by-nc'> $license</a></span><br>";
                            break;
                        case "Attribution-NonCommercial-ShareAlike":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by-nc-sa'> $license</a></span><br>";
                            break;
                        case "Attribution-NonCommercial-NoDerivs":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by-nc-nd'> $license</a></span><br>";
                            break;
                        case "Attribution-ShareAlike":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#cc-by-sa'> $license</a></span><br>";
                            break;
                        case "Bloomsbury Open";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        case "Coimbra University Press";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        case "De Gruyter";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        case "Free Documentation License";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        case "Newfound Press":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='https://newfoundpress.utk.edu/conditions-of-use/'>$license<a></span><br>";
                            break;
                        case "Open Access":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: $license</span><br>";
                            break;
                        case "OpenEdition licence for Books":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#openedition'> $license</a></span><br>";
                            break;
                        case "Public Domain":
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>:<a class='detailsLink' href='#' data-toggle='modal' data-target='#publicdomain'> $license</a></span><br>";
                            break;
                        case "University of Adelaide Press";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        case "Various Creative Commons Licenses";
                            $resultsHTML .= "<span class='license'><strong>Usage Rights</strong>: <a class='detailsLink' href='$license_url'>$license<a></span><br>";
                            break;
                        default:
                            break;
                    } 

                if($pub_date != "") {
                    $resultsHTML .= "<span class='pub_date'><strong>Publication Date</strong>: $pub_date</span><br>";
                }

                $resultsHTML .= "<span class='item_record'><a class='detailsLink' href='itemRecord.php?id=$id'><i class='fas fa-info-circle'></i> View Item Record</a></span>";
                $resultsHTML .= "<div style='padding-bottom:3px;'></div>";

                $resultsHTML .= "</div>";

                $resultsHTML .= "<div class='col-md-2'>";
                    if($image != "") {
                        $resultsHTML .=  "<a href='$link'><image src='$image' class='img-fluid coverImage' alt='$title' /></a>";
                    }
                $resultsHTML .= "</div>";

                $resultsHTML .= "</div>";
                $resultsHTML .= "<hr>";

            }

        return $resultsHTML;
    }

}

?>

这是我的search.php文件的代码,其中显示结果和过滤器:

<?php   
include("config.php");
include("classes/resultsProvider.php");

$term = isset($_GET["term"]) ? $_GET["term"] : "";

$type_search = isset($_GET['type']) ? $_GET['type'] : "";
$subject_search = isset($_GET['subject']) ? $_GET['subject'] : "";
$source_search = isset($_GET['source']) ? $_GET['source'] : "";   
$license_search = isset($_GET['usage']) ? $_GET['usage'] : "";     
$review_search = isset($_GET['review']) ? $_GET['review'] : "";
$isbn_search = isset($_GET['isbn_number']) ? $_GET['isbn_number'] : "";

$page = isset($_GET["page"]) ? $_GET["page"] : 1;

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>SOAR</title>
<?php
include("header.php");
include("searchBar.php"); 
include("filters.php"); 
?>

<div class="container">
<div class='row filterDisplayRow'>
    <?php
    $typeFilter = $term . $filter_source . $filter_license . $filter_subject . $filter_review;
    $subjectFilter = $term . $filter_source . $filter_license . $filter_type . $filter_review;
    $sourceFilter = $term . $filter_license . $filter_subject . $filter_type . $filter_review;
    $usageFilter = $term . $filter_subject . $filter_type . $filter_source . $filter_review;
    $reviewedFilter = $search_term . $filter_subject . $filter_license . $filter_type . $filter_source;

    if ($type_search != ""){
        echo "<div class='filterButton' class='btn-danger filterName'><a href='search.php?term=$typeFilter'/>$type_search <i class='far fa-times-circle'></i></a></div>";
    }
    if ($subject_search != ""){
        echo "<div class='filterButton' class='btn-danger filterName'><a href='search.php?term=$subjectFilter'/>$subject_search <i class='far fa-times-circle'></i></a></div>";
    }
    if ($source_search != ""){
        echo "<div class='filterButton' class='btn-danger filterName'><a href='search.php?term=$sourceFilter'/>$source_search <i class='far fa-times-circle'></i></a></div>";
    }
    if ($license_search != ""){
        echo "<div class='filterButton' class='btn-danger filterName'><a href='search.php?term=$usageFilter'/>$license_search <i class='far fa-times-circle'></i></a></div>";
    }
    if ($review_search != ""){
        echo "<div class='filterButton' class='btn-danger filterName'><a href='search.php?term=$reviewedFilter'/>$review_search <i class='far fa-times-circle'></i></a></div>";
    }
    ?>
</div> 

</div>


<div class="container content-container">
    <div class="card card-content">
        <div class="card-body">

        <?php
        $resultsProvider = new resultsProvider($conn);
        $pageSize = 25;

        $numResults = $resultsProvider->getNumResults($term);
        $search_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        echo "<div class='row'>";
            echo "<div class='col-md-10'>";
                echo "<h4><strong>" . number_format($numResults) . " results found</strong></h4>";
            echo "</div>";

            if($numResults == 0) {?>  
                <script>window.location.href = "noResults.php";</script>
            <?php }

            echo "<div class='col-md-2'>";
                echo "<button type='button' class='btn btn-searchLink float-right' data-toggle='modal' data-target='#searchLink'><i class='fas fa-link'></i> Results Link</button>";
            echo "</div>";
        echo "</div>";
        echo "<hr size='2' noshade>";

        echo $resultsProvider->getResultsHTML($page, $pageSize, $term);

        include("pagination.php");
        ?>

        </div>
    </div>
</div>
<?php include("modals.php"); ?>        
<?php include("footer.php"); ?>
</body>
</html>
php mysql pdo
2个回答
0
投票

URL查询

您使用以下代码构建URL:

$soar_array = array();
if ($type_search != ""){
    $filter_type = "&type=$type_search";
    $soar_array[] = "type = '$type_search'";
}

if ($subject_search != ""){
    $filter_subject = "&subject=$subject_search";
    $soar_array[] = "subject = '$subject_search'";
} 

if ($source_search != ""){
    $filter_source = "&source=$source_search";
    $soar_array[] = "source = '$source_search'"; 
} 

if ($license_search != ""){
    $filter_license = "&usage=$license_search";
    $soar_array[] = "license = '$license_search'";
}

if ($review_search != ""){
    $filter_review = "&review=$review_search";
    $soar_array[] = "review = '$review_search'";
}

if ($isbn_search != ""){
    $soar_array[] = "isbn_number = '$isbn_search'";
}

并像这样使用它

    while($row = $source_query->fetch(PDO::FETCH_ASSOC)) {
        $source_name = $row['source'];
        $total_source = number_format($row['total']);
        $all = urlencode($term) . $filter_license . $filter_subject . $filter_review . $filter_type;

        echo "<a class='dropdown-item' href='search.php?term=$all&source=$source_name'>$source_name ($total_source)</a>";
    }

在您的情况下,$ all将被编码,但是它将以编码后的&开头。我现在不确定这是否有问题,但是可能在您的代码中有问题。

逻辑错误

public function getNumResults($ term){

    $query = $this->conn->prepare("SELECT COUNT(*) as total
            FROM oer_search WHERE title LIKE :term
            OR type LIKE :term
            OR subject LIKE :term
            OR source LIKE :term
            OR author LIKE :term
            OR license LIKE :term
            OR isbn_number LIKE :term
            OR e_isbn_number LIKE :term");

    $searchTerm = "%". $term . "%";
    $query->bindParam(":term", $searchTerm);
    $query->execute();

    $row = $query->fetch(PDO::FETCH_ASSOC);
    return $row["total"];
}

如果您搜索多个词,则需要AND,而不是OR。对于您当前的代码,如果有任何过滤器通过,那么结果将通过,但是,这可能不是您的目标。您还可以使用$ term过滤所有内容,这是不正确的,因为您对单独的元素具有单独的搜索条件。您需要确保分离单独的条件。让我们再看一下搜索链接的生成方式。基本上$term将包含所有参数。您需要先解析$term,然后将每个术语用作过滤器。

SQL注入漏洞

永远不要像不安全地将用户输入提供给查询那样信任用户输入。始终使用PDO。

单独关注

我们都很难阅读您所提问题的代码,因为它太长了。我确定您遇到了同样的问题,这就是您无法确定问题确切位置的原因。不要过多地将HTML标记与PHP后端逻辑混合在一起,当然也不要将其与SQL混合使用。

避免代码重复

重复代码始终是导致错误的潜在原因。如果您复制粘贴相同的代码,则该代码的每个“版本”将具有其自己的生命周期和自身的演变,从而导致不一致和错误。


-1
投票

我通常以这种方式创建高级搜索栏

HTML

<form name="frmSearch" method="post" action="index.php">
    <input type="hidden" id="advance_search_submit" name="advance_search_submit" value="<?php echo $advance_search_submit; ?>">
    <div class="search-box">
        <label class="search-label">With Any One of the Words:</label>
        <div>
            <input type="text" name="search[with_any_one_of]" class="demoInputBox" value="<?php echo $with_any_one_of; ?>"  />
            <span id="advance_search_link" onClick="showHideAdvanceSearch()">Advance Search</span>
        </div>              
        <div id="advanced-search-box" <?php if(empty($advance_search_submit)) { ?>style="display:none;"<?php } ?>>
            <label class="search-label">With the Exact String:</label>
            <div>
                <input type="text" name="search[with_the_exact_of]" id="with_the_exact_of" class="demoInputBox" value="<?php echo $with_the_exact_of; ?>"   />
            </div>
            <label class="search-label">Without:</label>
            <div>
                <input type="text" name="search[without]" id="without" class="demoInputBox" value="<?php echo $without; ?>" />
            </div>
            <label class="search-label">Starts With:</label>
            <div>
                <input type="text" name="search[starts_with]" id="starts_with" class="demoInputBox" value="<?php echo $starts_with; ?>" />
            </div>
            <label class="search-label">Search Keywords in:</label>
            <div>
                <select name="search[search_in]" id="search_in" class="demoInputBox">
                    <option value="">Select Column</option>
                    <option value="title" <?php if($search_in=="title") { echo "selected"; } ?>>Title</option>
                    <option value="description" <?php if($search_in=="description") { echo "selected"; } ?>>Description</option>
                </select>
            </div>
        </div>

        <div>
            <input type="submit" name="go" class="btnSearch" value="Search">
        </div>
    </div>
</form>

PHP

<php
    $conn = mysqli_connect("localhost", "root", "", "db");  
    $with_any_one_of = "";
    $with_the_exact_of = "";
    $without = "";
    $starts_with = "";
    $search_in = "";
    $advance_search_submit = "";

    $queryCondition = "";
    if(!empty($_POST["search"])) {
        $advance_search_submit = $_POST["advance_search_submit"];
        foreach($_POST["search"] as $k=>$v){
            if(!empty($v)) {

                $queryCases = array("with_any_one_of","with_the_exact_of","without","starts_with");
                if(in_array($k,$queryCases)) {
                    if(!empty($queryCondition)) {
                        $queryCondition .= " AND ";
                    } else {
                        $queryCondition .= " WHERE ";
                    }
                }
                switch($k) {
                    case "with_any_one_of":
                        $with_any_one_of = $v;
                        $wordsAry = explode(" ", $v);
                        $wordsCount = count($wordsAry);
                        for($i=0;$i<$wordsCount;$i++) {
                            if(!empty($_POST["search"]["search_in"])) {
                                $queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $wordsAry[$i] . "%'";
                            } else {
                                $queryCondition .= "title LIKE '" . $wordsAry[$i] . "%' OR description LIKE '" . $wordsAry[$i] . "%'";
                            }
                            if($i!=$wordsCount-1) {
                                $queryCondition .= " OR ";
                            }
                        }
                        break;
                    case "with_the_exact_of":
                        $with_the_exact_of = $v;
                        if(!empty($_POST["search"]["search_in"])) {
                            $queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $v . "%'";
                        } else {
                            $queryCondition .= "title LIKE '%" . $v . "%' OR description LIKE '%" . $v . "%'";
                        }
                        break;
                    case "without":
                        $without = $v;
                        if(!empty($_POST["search"]["search_in"])) {
                            $queryCondition .= $_POST["search"]["search_in"] . " NOT LIKE '%" . $v . "%'";
                        } else {
                            $queryCondition .= "title NOT LIKE '%" . $v . "%' AND description NOT LIKE '%" . $v . "%'";
                        }
                        break;
                    case "starts_with":
                        $starts_with = $v;
                        if(!empty($_POST["search"]["search_in"])) {
                            $queryCondition .= $_POST["search"]["search_in"] . " LIKE '" . $v . "%'";
                        } else {
                            $queryCondition .= "title LIKE '" . $v . "%' OR description LIKE '" . $v . "%'";
                        }
                        break;
                    case "search_in":
                        $search_in = $_POST["search"]["search_in"];
                        break;
                }
            }
        }
    }
    $orderby = " ORDER BY id desc"; 
    $sql = "SELECT * FROM links " . $queryCondition;
    $result = mysqli_query($conn,$sql);
?>

SQL

-表links的表结构>

CREATE TABLE `links` (
  `id` int(8) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `votes` tinyint(2) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table `links`



INSERT INTO `links` (`id`, `title`, `description`, `votes`) VALUES
(1, 'Favorite Star Rating with jQuery', 'This tutorial is for doing favorite star rating using jQuery. It displays list of HTML stars by using li tags. These stars are highlighted by using CSS and jQuery based on the favorite rating selected by the user.', 1),
(2, 'PHP RSS Feed Read and List', 'PHP\'s simplexml_load_file() function is used for reading data from xml file. Using this function, we can parse RSS feed to get item object array.', 0),
(3, 'jQuery AJAX Autocomplete - Country Example', 'Autocomplete feature is used to provide auto suggestion for users while entering input. It suggests country names for the users based on the keyword they entered into the input field by using jQuery AJAX.', 0),
(4, 'PHP CRUD with Search and Pagination', 'We have search options for searching the Name and Code columns by the given keywords posted via the search form. The search keyword is used to find match with the values of corresponding columns by using MySQL LIKE clause.', 0),
(5, 'DropDown with Search using jQuery', 'Search is an useful feature for a HTML dropdown list. Especially it will increase user convenience to select items from the dropdown having long list. In this tutorial, we are going to list country dropdown with a search option.', 0),
(6, 'PHP MySQL Date Range Search with jQuery DatePicker', 'how to search database records date between two given ranges. It will return the filtered results from database based on these dates input.', 0);

-- Indexes for table `links`
ALTER TABLE `links`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `links`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
COMMIT;

我不太记得,但我认为这个例子来自tutorialsrepublic

最诚挚的问候

山南

© www.soinside.com 2019 - 2024. All rights reserved.