[英]Sorting Alphabetically in PHP from Database
I'm trying to sort a list alphabetically, this list is taken from a MySQL Database but I can only arrange the information in ascending or descending order. 我正在尝试按字母顺序对列表进行排序,该列表取自MySQL数据库,但我只能按升序或降序排列信息。 This is the code I'm currently using: 这是我当前正在使用的代码:
if(isset($_GET['cat_id']))
{
$cat_id=$_GET['cat_id'];
$query="SELECT sub_cat_id,sub_cat_name FROM tbl_sub_category WHERE cat_id='". $cat_id."' ORDER BY tbl_sub_category.sub_cat_id DESC LIMIT $number_of_posts";
}
else if(isset($_GET['sub_cat_id']))
{
$sub_cat_id=$_GET['sub_cat_id'];
$query="SELECT * FROM tbl_directory WHERE d_subcat_id='". $sub_cat_id."' ORDER BY tbl_directory.d_id DESC LIMIT $number_of_posts";
}
else if(isset($_GET['sub_sub_cat_id']))
{
$sub_sub_cat_id=$_GET['sub_sub_cat_id'];
}
else if(isset($_GET['directory_id']))
{
$directory_id=$_GET['directory_id'];
$query="SELECT * FROM tbl_directory WHERE d_id='". $directory_id."'";
}
else
{
$query="SELECT cid,category_name,category_image FROM tbl_category ORDER BY tbl_category.cid DESC LIMIT $number_of_posts";
}
You need to sort by name, not by id. 您需要按名称而不是ID排序。
Note: Put the appropriate field names where necessary. 注意:如有必要,请放置适当的字段名称。
Corrected code: 更正的代码:
<?php
if(isset($_GET['cat_id'])) {
$cat_id=$_GET['cat_id'];
$query="SELECT sub_cat_id,sub_cat_name FROM tbl_sub_category WHERE cat_id='". $cat_id."' ORDER BY tbl_sub_category.sub_cat_name DESC LIMIT $number_of_posts";
}
else if(isset($_GET['sub_cat_id'])) {
$sub_cat_id=$_GET['sub_cat_id'];
$query="SELECT * FROM tbl_directory WHERE d_subcat_id='". $sub_cat_id."' ORDER BY tbl_directory.d_NAME_FIELD DESC LIMIT $number_of_posts";
}
else if(isset($_GET['sub_sub_cat_id'])) {
$sub_sub_cat_id=$_GET['sub_sub_cat_id'];
}
else if(isset($_GET['directory_id'])) {
$directory_id=$_GET['directory_id'];
$query="SELECT * FROM tbl_directory WHERE d_id='". $directory_id."'";
}
else {
$query="SELECT cid,category_name,category_image FROM tbl_category ORDER BY tbl_category.category)name DESC LIMIT $number_of_posts";
}
由于usermesam0023刚刚更改了这一行ORDER BY tbl_directory.directory_name
而不是directory_id
所以它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.