简体   繁体   中英

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?

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. The default would be ASC (ascending).

The ORDER BY only functions correctly in case your date is correctly stored, not as a VARCHAR .

You are not using *mysqli_fetch_array* to pull comments, you are using it to put the results into an 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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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