在我的数据库中,我有这些话: 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/