我正在尝试对表中的 MySQL 数据进行排序,但我的问题是我的查询正在对我的表看起来像的所有数据进行排序
Word | Meaning | Synonym | Antonym
definitely | without doubt | certainly |possibly
great | of an extent, amount | considerable |little
zeal | great energy | passion | indiference
zealot | a person who is fanatical|fanatic | moderate
zealous | having or showing zeal. | fervent | apathetic
所以当我搜索时,让我们说以 H
z
开头的单词然后我得到:
Word | Meaning | Synonym | Antonym
zeal | great energy | passion | indiference
zealot | a person who is fanatical|fanatic | moderate
zealous | having or showing zeal. | fervent | apathetic
现在我想对这些搜索到的数据进行排序,但我的排序查询是对所有数据进行排序。
我的存储过程如下所示:
CREATE DEFINER=`root`@`localhost` PROCEDURE `SortContent`()
BEGIN
SELECT * from dictionarysearch ORDER BY word ASC;
END
我的 PHP 代码是这样的:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here i'm calling a function which is calling the store procedure
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><a href="view.php?q=<?php echo $row['id'];?>"><?php echo $row['word'];?></a></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><a href="admin.php?id1=<?php echo $row['id'];?>"><i class="fa fa-edit"></i></a> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
</table>
所以我想知道如何编写一个查询,以便它只对选定的数据进行排序,并且我已经设置了 id autoincrement。
不需要为此使用存储过程。我建议以下代码对您有用...
<?php
if(isset($_GET['search_btn']) && strlen($_GET['search'])){
$search = mysqli_escape_string($conn,$_GET['search']);
$sql = "SELECT * FROM dummydata WHERE info LIKE '".$search."%'";
if(isset($_GET['sort']) && in_array($_GET['sort'], array('ASC', 'DESC'))){
$sort=$_GET['sort'];
$sql .= " ORDER BY info ".$sort;
}
//echo "<h3>".$sql."</h3>";
if (($result=mysqli_query($conn,$sql))!==false) {
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<tbody>
<?php
while ($row=mysqli_fetch_assoc($result)){
//echo "<pre>".var_export($row,true)."</pre>";
?>
<tr>
<td><a href="view.php?q=<?php echo $row['id'];?>"><?php echo $row['word'];?></a></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td>Your action url here.... </td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
} else {
echo "<h3>Problem with SQL</h3>";
}
}
?>
希望对您有所帮助。