首页 > 解决方案 > PHP 搜索功能无法返回结果

问题描述

我正在重构 PHP 脚本(从 mysqli 迁移到 PDO)。它的目的是为网站创建资源列表并允许用户过滤它们。还有一个基本的搜索功能。重构脚本中的所有内容都运行良好,除了搜索功能。尝试搜索不会返回任何结果。该信息存在于数据库中,我在 Apache 日志中找不到任何错误。这是代码:

require_once('web_misc_config');

...    

$search=(isset($_GET['search']) ? $_GET['search'] : null);
$search= addslashes($search); 
$searchletter=(isset($_GET['searchletter']) ? $_GET['searchletter'] : null);

//This while loop creates the searched version of the A to Z list.
if (!empty($search)){
    $result = $con->prepare("SELECT title,summary,url,coverage,format FROM 

    dbs where title like :search or summary like :search");
    $result->bindParam(':search', $search, PDO::PARAM_STR);
    $result->execute();

    while($row = $result->fetch())
    {
        $url=$row['url'];
        $title=$row['title'];
        $summary=$row['summary'];
        $coverage=$row['coverage'];
        $format=$row['format'];

        echo ('<p><h6><a href="' . $url . '">' . $title . '</a></h6>
                        <br />' . $summary . '</p>');
    } 
}

//This block creates the filtered and searched version of the list.
elseif (!empty($searchletter)) {
    $result = $con->prepare("SELECT title,summary,url,coverage,format,fletter FROM dbs where fletter = :searchletter");
    $result->bindParam(':searchletter', $searchletter);
    $result->execute();

    while($row = $result->fetch())
    {
        $url=$row['url'];
        $title=$row['title'];
        $summary=$row['summary'];
        $coverage=$row['coverage'];
        $format=$row['format'];

        echo ('<p><h6><a href="' . $url . '">' . $title . '</a></h6>
                        <br />' . $summary . '</p>');
    }
}  

//This block loop creates the inital A to Z list.
else {
    $result = $con->prepare("SELECT title,summary,url,coverage,format FROM dbs");
    $result->execute();

    while($row = $result->fetch())
    {
        $url=$row['url'];
        $title=$row['title'];
        $summary=$row['summary'];
        $coverage=$row['coverage'];
        $format=$row['format'];

        echo ('<p><h6><a href="' . $url . '">' . $title . '</a></h6>
                        <br /> ' . $summary . '</p>');
    } 
}   
$result = null;
$con = null;

ELSEIF 和 ELSE 块工作正常。初始的未过滤列表已填充,用户可以按字母顺序对其进行过滤。此处包含它们是为了完整性和比较。问题在于 IF 块中的 while 循环(在第一条评论下)。它评估为假,导致出现空白屏幕而不是搜索结果。只要从数据库中检索到结果,它就应该评估为真。谁能看到我可能错过的东西?

标签: phpmysqlpdo

解决方案


由于$search不包含任何通配符,LIKE将被视为=并查找完全匹配。如果要在列中的任何位置搜索它,则需要添加通配符。

if (!empty($search)){
    $search = "%$search%";
    $result = $con->prepare("SELECT title,summary,url,coverage,format 
        FROM dbs 
        where title like :search or summary like :search");
    $result->bindValue(':search', $search, PDO::PARAM_STR);
    $result->execute();

推荐阅读