php mysql按日期排序(最近)

时间:2015-10-31 04:03:13

标签: php android mysql sql api

我现在的代码是从SQL中获取移动应用程序中的数据,首先添加显示,我需要将其设置为显示最后添加为我的Android应用程序中的第一个。我有api代码如下,最近根据我的要求显示,但对于cid和援助我需要最新的(必须显示最近作为第一)。我的代码如下 感谢

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

error_reporting(0);

mysql_query("SET NAMES 'utf8'");    

if(isset($_GET['cid']))
{
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
{

    $query="SELECT cid,category_name,category_image FROM tbl_category";


}
$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;

  }
}

    /* output in format */

 //echo $val= str_replace('\\/', '/', json_encode($set));
     header( 'Content-Type: application/json; charset=utf-8' );

    echo str_replace('\\/', '/',json_encode($set,JSON_UNESCAPED_UNICODE));


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

    $author_id=$_GET['aid'];        

        $qry="SELECT * FROM tbl_quotes
    LEFT JOIN tbl_author ON tbl_quotes.aid= tbl_author.author_id 
    where tbl_quotes.aid='".$author_id."'";

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

    $qry="SELECT author_id,author_name,author_image FROM tbl_author";

}

$resultouter = mysql_query($qry);

$author_set = array();

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

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

    $author_set['Quotes'][] = $link;
  }
}

// echo $value= str_replace('\\/', '/', json_encode($author_set));

    /* output in format */

    header( 'Content-Type: application/json; charset=utf-8' );

    echo str_replace('\\/', '/',json_encode($author_set,JSON_UNESCAPED_UNICODE));
}
?>

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";

如果您的列数据类型不是datedatetime我们cast(),那么: -

CAST(column_name AS DATETIME);
CAST(column_name AS DATE);

答案 1 :(得分:0)

也可以使用order by作为日期。

 ORDER BY tbl_quotes.id DESC, DATE(your_date_column) desc

另请参阅此documentation了解更多信息