2

I have very basic php question. I am fetching data from database and printing them with some styling row by row. The problem is that these data represent news and I would like them to be printed in reverse order (the last row I fetch should be printed first). I am not sure if I can fetch the whole table at once and them apply the reverse function (I tried it but it didnt work).

Here is my code:

<?php
                include 'dbconnect.php';
                $data = mysql_query("SELECT * FROM news") or die(mysql_error()); 

                while($info = mysql_fetch_array( $data )) 
                {
                echo '<article><h3> '.$info['subject'].'</h3><div id="date">'.$info['date']. '</div>';
                echo '<p>'.$info['news']. '</p></article>';

                } 
?>

I tried something like this:

$data = [];
array_push($array, $info);

inside the while loop and then printing it but it didnt turn out to work. Thanks for any answer!

2

6 Answers 6

3

You should to that directly in sql and not afterwards in php:

SELECT * FROM news ORDER BY date DESC

You should also switch to PDO (or mysqli) as the mysql_* functions are deprecated.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$data = mysql_query("SELECT * FROM news ORDER BY date DESC") or die(mysql_error());

1 Comment

It fixes the ordering, but 'SELECT *' is a very bad practice. While it the code may seem to work with mysql_fetch_assoc(), using it with mysql_fetch_array() is downright silly.
2
"SELECT * FROM news ORDER BY id DESC"

You can use this, if you have an ID for every news.

Comments

0

array_reverse() function of PHP or ORDER BYid(or time/date column) DESC in mysql query

Comments

0
mysql_query("SELECT * FROM news ORDER BY date DESC")

I believe that is what you are looking for.

Comments

0
$query = "SELECT * FROM news ORDER BY date DESC";
$data = mysql_query($query) or die(mysql_error());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.