【发布时间】:2019-04-03 23:46:13
【问题描述】:
我正在重构一个 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 循环(在第一条评论下)。它评估为假,导致出现空白屏幕而不是搜索结果。只要从数据库中检索到结果,它就应该评估为真。谁能看到我可能错过的东西?
【问题讨论】:
-
在使用
LIKE时,您可能希望在绑定中使用%。看看这是否有助于获取一些行。这是答案:stackoverflow.com/questions/2722136 -
在使用准备好的语句时,不应使用
addslashes()。