php - 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 循环(在第一条评论下)。它评估为假,导致出现空白屏幕而不是搜索结果。只要从数据库中检索到结果,它就应该评估为真。谁能看到我可能错过的东西?
解决方案
由于$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();
推荐阅读
- email - Microsoft Graph 发送电子邮件 api 对话索引不同
- ionic-framework - 使用主要功能时电容器文件系统返回错误
- html - 如何为日期类型的输入字段添加清除按钮
- android - 如何创建自定义警告以显示在 Android 项目的 build.gradle 文件中?
- flutter - 使用 youtube_player_iframe Flutter 观看 YouTube 视频
- flutter - `Drawer` 中的 Flutter 本地化导致`Null check operator used on a null value` 错误
- node.js - Firebase Cloud onCall 函数始终返回 null
- python - Python多线程程序给出了意外的输出
- python - 两个凸包的体积重叠
- python - 如何从python中的数据框中获取子集数据框?