简体   繁体   English

PHP:我可以选择返回数据库结果的顺序

[英]PHP: Can I choose the order in which database results are returned

I am using using *mysqli_fetch_array()* to pull comments from my database but is there anyway to pull them out in the order of newest first? 我正在使用* mysqli_fetch_array()*来从我的数据库中提取注释但是无论如何要按照最新的顺序将它们拉出来?

Here is my code: 这是我的代码:

while($row_comments = mysqli_fetch_array($result_get_comments)){
?>
    <div class="itemFullWidth itemStyle">
        <p><?php echo $row_comments['comment_author'];?> says:
        <br>
        <?php echo $row_comments['comment_content'] ?>
        </p>
    </div>

<?php
}
?>

Speaking of fields 说到田野

SELECT field1, field5, fieldXX, field_last FROM ...
   //  ^ here your order goes

But if you want to order returned rows , 但是如果你想订购退回的

SELECT ... FROM ... ORDER BY id DESC
// DESC means biggest value first ^

SELECT * FROM myTable ORDER BY date DESC

More about it here . 更多关于它的信息

Note that DESC (descending) is important here in order to get the newest. 请注意, DESC (降序)在这里很重要,以获得最新的。 The default would be ASC (ascending). 默认ASC (升序)。

The ORDER BY only functions correctly in case your date is correctly stored, not as a VARCHAR . ORDER BY仅在正确存储日期时才能正常运行,而不是作为VARCHAR

You are not using *mysqli_fetch_array* to pull comments, you are using it to put the results into an array. 您没有使用* mysqli_fetch_array *来提取注释,您正在使用它将结果放入数组中。 You are likely using *mysqli_query* to fetch the comments, so you need to be looking there, not in your array function that merely formats the already fetched and sorted results... 您可能正在使用* mysqli_query *来获取注释,因此您需要在那里查找,而不是在您的数组函数中仅仅格式化已经获取和排序的结果...

Something like: 就像是:

"SELECT fields,go,here FROM comments ORDER BY id DESC

will work, if you're using an ID, or you can sort them by *comment_date* for example, if you have such a field, etc. 如果您正在使用ID,则可以使用,或者您可以通过* comment_date *对它们进行排序,例如,如果您有这样的字段等。

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

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