【问题标题】:PHP MySQL search functionPHP MySQL 搜索功能
【发布时间】:2014-04-23 19:13:31
【问题描述】:

我正在为一个学校项目写博客,我即将完成,我想添加一个搜索功能,但遇到了一些问题,但可能不是很难解决。

所以我将在下面发布我的代码并解释我猜。

Header.php //每个页面都需要,它是一个模板

<form method="post" action="index.php">
    <input type="text" name="search" placeholder="Search..." />
    <input type="submit" value="Search" />
</form>

Index.php //我希望结果显示在哪里。

$searchword = $_POST['search'];
$query = mysqli_query($con, "SELECT * FROM posts ORDER BY postID desc LIMIT $start, $limit");

if ($searchword != "") {
    $query = mysqli_query($con, "SELECT * FROM posts WHERE text LIKE '%$searchword%' ORDER BY postID desc LIMIT " . $start, $limit);
}

while($row = mysqli_fetch_array($query))
{ //This is where all the blog posts are outputted. 
  //And where I want the results to show up as well, but instead of all posts, 
  //when something is searched for, if possible.

好的,所以问题是我不知道如何执行 $query。 我试过这个

action="anotherpage.php" 

并像这样编写查询

$searchword = $_POST['search'];
$query = mysqli_query($con, "SELECT * FROM posts WHERE text LIKE '%$searchword%'");
while($row = mysqli_fetch_array($query)) {

它工作了,但我最好不想打开另一个页面来显示结果,现在在 index.php 页面上我不知道该怎么做,因为我有

LIMIT " . $start, $limit); //for my pagination.
and
ORDER BY //in the query as well, I cant get it to work. 

我也试过了

if (!empty($searchword)) //Dont really know if that's how you do it, but didn't work either

我希望我提供了足够的信息。 基本上我想在我的第一页上看到我的所有帖子,如果我搜索某些内容,我只想显示结果,但在同一页面上并带有我的分页。 顺便说一句,这个网站没有上线,只是一个学校项目,所以不要太担心sql注入什么的。 提前致谢!

【问题讨论】:

  • 您想将搜索结果动态添加到当前页面吗?听起来你需要学习 AJAX。从这里开始:learn.jquery.com/ajax
  • 嗯,我不知道,我以前在cshtml中做过,只是当搜索框中发布了某些内容时,查询会更改为博客文本包含搜索词的位置

标签: php mysql function search sql-like


【解决方案1】:

你的动作应该是这样的:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
        // ..form fields..

</form>

它总是会返回到当前页面。

【讨论】:

  • 您需要在 echo 语句周围加上 &lt;?php ... ?&gt; 代码标签。
  • 某时卡住了一整天。这解决了它。谢谢你
猜你喜欢
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 2012-05-05
相关资源
最近更新 更多