PHP/MySQL : how to display the words before and after the searched item

标签 php html mysql sorting

在我的数据库中,我有这些话: AA、AB、AC、AD、AE、AF、AG

我搜索“AD”为:

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

我想按字母顺序对数据库中的所有单词进行排序。然后只显示搜索到的值(即AD)和之前​​的词和之后的词。像这样:

  • 交流
  • 广告
  • AE

这是我到目前为止所写的内容(非常感谢您的帮助):

<?php
include('includes/db_AF.php'); //includes the db credentials
$connection = @new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if ($connection->connect_error) {
  die('Connect Error: ' . $connection->connect_error);
} else {

  $search=$_POST["search"];

  $query="SELECT word FROM wordtable2
  WHERE word like '%' 
  ORDER BY word ASC";   // I am sorting all the words in the database                       

  $result_obj = '';
  $result_obj = $connection->query($query);         

  while($result = $result_obj->fetch_array(MYSQLI_ASSOC)) { 
    $items[] = $result;
  }                             

  foreach ($items as $item) {
    echo $item['word']; //Here I need to echo the results, but don't know how to
  }
}
?>

最佳答案

在 SQL 中可能有更优雅的方法来执行此操作,但我能想到的最简单的方法实际上涉及两个查询。

用你的例子...

假设您的数据库有以下条目

AA, AB, AC, AD, AE, AF

按照你的例子,你有值 AD 并且你想检索 AC 和 AE。

首先,做这样的查询...

SELECT word FROM wordtable2
    WHERE word > 'AD'
    ORDER BY word ASC
    LIMIT 1;

然后像这样查询...

SELECT word FROM wordtable2
    WHERE word < 'AD'
    ORDER BY word DESC
    LIMIT 1;

关于PHP/MySQL : how to display the words before and after the searched item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19307869/

相关文章:

php - 防止直接访问 php 文件但允许包含它

php - [function.fopen] : failed to open stream: HTTP request failed! HTTP/1.1 401 未经授权

java - 如何从 JSP 页面返回到 index.html(登录页面)?

mysql - 相当于 MySQL 中的 varchar(max)?

mysql - 如何获取 SELECT 中任何数据的日期

mysql - 这个sql中的where子句会放在哪里?

java - 如何消除 KVM VM 中 java 和 php 进程间进程间通信的 tcp-ip 发送延迟

html - 如何将点击事件分配给指令外的元素?

HTML/CSS : Create a div that always fills the entire page. .. 然后里面有一个可调整大小的 div?

php - 如何用 PHP 用大写字母分解字符串?