简体   繁体   English

从mysql降序排序

[英]sort in descending order from mysql

So I was trying to write code in PHP. 所以我试图用PHP编写代码。 My goal was to write a generic code for mysql get operations. 我的目标是为mysql get操作编写通用代码。 For an instance I would like to pass the table name and from and to values to get the result back in the form of JSON like below. 对于一个实例,我想将表名和值从和传递给值,以便以JSON形式返回结果,如下所示。

function get($table, $from, $to) {
     $q = mysqli_query('select * from '.$table.' limit '. $from.', '.$to);
     // do some more 
     return json_encode($arr);
}

The above code will give the result. 上面的代码将给出结果。 as expected. 如预期的那样。 Now the problem I face is when I want my code to return the values depending in the descending order depending on the auto_incrment ed column of my table. 现在我面临的问题是,当我希望代码根据表的auto_incrment ed列以降序返回值时。 I'm completely stuck at this point. 我完全被困在这一点上。

I used to do like this when I didn't wanted a gereric code. 当我不想使用通用代码时,我曾经这样做。

select * from tablename order by auto_inc_col limit 0,10

I tried with google to get some answers regarding the same. 我试图与谷歌获得有关相同的一些答案。 But couldn't get it. 但无法理解。 As per my experience I should specify the column name which I'm unable to with the code I'm trying to write now. 根据我的经验,我应该使用现在尝试编写的代码指定无法使用的列名。

Now my question is this. 现在我的问题是这个。 Is it possible to specify a column name dynamically through any of the mysql queries. 是否可以通过任何mysql查询动态指定列名。 If possible How? 如果可能的话如何? Or should I quit this generic code and start writing the code for each table seperately? 还是应该退出此通用代码,并开始分别为每个表编写代码? Please help me to get out of this problem. 请帮助我摆脱这个问题。

I'm not quite sure what you are asking, but wouldn't something like this help ? 我不太确定您要问什么,但是这样的帮助不是吗?

function get($table, $from, $to) {
    $q = mysqli_query('select * from '.$table.' order by auto_inc_col DESC limit '. $from.', '.$to);

You could even have variables $sortCol and $sortOrder. 您甚至可以使用变量$ sortCol和$ sortOrder。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM