php mysql按DESC排序

时间:2017-01-07 10:03:26

标签: php mysql sql

我有api代码,如下所示,最近根据我的要求显示但是对于cid和援助我需要和最新一样(必须最近显示为第一个)。我的代码如下所示,谢谢

<?php include("includes/connection.php");

mysql_query("SET NAMES 'utf8'");

if(isset($_GET['language_id']))
{ 
    $query="SELECT cid,category_name,category_image FROM tbl_category WHERE lid='".$_GET['language_id']."'";

}
else if(isset($_GET['cat_id']))
{

    $cat_id=$_GET['cat_id'];        

        $query="SELECT * FROM tbl_quotes
    LEFT JOIN tbl_category ON tbl_quotes.cat_id= tbl_category.cid 
    where tbl_quotes.cat_id='".$cat_id."'";

}
else if(isset($_GET['latest']))
{
    $limit=$_GET['latest'];     
    $query="SELECT * FROM tbl_quotes
    LEFT JOIN tbl_category ON tbl_quotes.cat_id= tbl_category.cid 
    ORDER BY tbl_quotes.id DESC LIMIT $limit";
}
else if(isset($_GET['home_banner']))
{

    $query="SELECT app_name,app_url,app_image FROM tbl_banner";     

}
else if(isset($_GET['about_app']))
{

    $query="SELECT app_name,app_logo,app_email,app_website,app_description FROM tbl_settings";      

}
else
{

    $query="SELECT id,language_name FROM tbl_language";


}
$resouter = mysql_query($query);

$set = array();

$total_records = mysql_num_rows($resouter);
if($total_records >= 1){

  while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){

    $set['Quotes'][] = $link;
  }
}
else
{
    $set['Quotes'][] = null;
}
 header( 'Content-Type: application/json; charset=utf-8' );
 echo $val= str_replace('\\/', '/', json_encode($set));

对此进行了实验性修正但无济于事

else if(isset($_GET['cat_id']))
{

    $cat_id=$_GET['cat_id'];        

        $query="SELECT * FROM tbl_quotes
    LEFT JOIN tbl_category ON tbl_quotes.cat_id= tbl_category.cid 
    where tbl_quotes.cat_id='".$cat_id."'";

}

尝试这一点也取得了成功php mysql sort by date (Recent)

这是链接api /api.php?cat_id=1

2 个答案:

答案 0 :(得分:2)

当您使用 SELECT语句查询表中的数据时,结果集不会按任何顺序排序。要对结果集进行排序,请使用 ORDER BY

像那样: -

ORDER BY column1 [ASC|DESC]

如下所示根据它更改代码: -

$query="SELECT * FROM tbl_quotes
    LEFT JOIN tbl_category ON tbl_quotes.cat_id= tbl_category.cid 
    ORDER BY tbl_quotes.id DESC,date DESC LIMIT $limit";

答案 1 :(得分:0)

感谢所有人 我试过这个并成功了

else if(isset($_GET['cat_id']))


$cat_id=$_GET['cat_id'];        

    $query="SELECT * FROM tbl_quotes
LEFT JOIN tbl_category ON tbl_quotes.cat_id= tbl_category.cid 
where tbl_quotes.cat_id='".$cat_id."' order by cid DESC";