我正在尝试为网站创建搜索工具。该网站包含文本帖子,因此数据库有一个表 post_record,其中包含字段 post_id、post_title、post_href 和 post_content。
现在的工作是,当用户在搜索字段中输入任何搜索关键字时,该关键字将针对所有帖子标题和帖子内容进行测试,并且在匹配的位置应返回所有这些行。以下是它的代码。问题是它只返回数据库的最后一行。
<table class="s_table">
<?php
require_once'config.php';
if(isset($_POST['search_btn']))
{
$mes = " ";
$search_key =" ";
$search_key = ($_POST['search_field']);
try
{
if(empty($search_key) && $search_key != " ")
{
echo $mes = "Enter the keyword you want to search.";
}
else
{
$result = $conn->prepare("SELECT * FROM post_record WHERE post_title LIKE '%".$search_key."%' OR post_content LIKE '%".$search_key."%'");
$result->execute();
$count=$result->rowCount();
$datas = $result->fetchAll();
if(!$count)
{
echo $mes = "No Result found. Try another keyword for search.";
}
else
{
foreach ($datas as $data)
{
echo "
<tr><td><b><u><a href='".$data['post_href']."'>".$data['post_title']."</a></b></u></td></tr><br>
<tr><td class='s_cont'>".$data['post_content']."</tr></td><br><br>";
}
}
}
}
catch(PDOException $e)
{
$mes = "Something Went Wrong! try again";
header("location:index.php");
}
}
$conn = null;
?>
一切工作正常,除了只显示数据库的最后一行。
现在数据库有 3 个帖子,出于测试目的,我尝试了一个我知道在所有帖子内容中都很常见的关键字,但它不起作用。仅提取和测试数据库的最后一行。
最佳答案
if(empty($search_key) && $search_key != "")
这个条件是错误的
两者都是不同的事情,永远不会实现。
您正在测试它是否为空,然后您正在测试它是否不为空
两者的 if 条件相同
关于PHP 搜索表单仅测试数据库的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283381/