user1610205
user1610205

Reputation: 25

SELECT * FROM table_name ORDER BY column_name?

ok so i coded in a news section and everytime i insert new news,its shows below the old one. i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.

so row with id = 2 will be here

so row with id = 1 will be here

thats how i want it to be, instead of it being like this

so row with id = 1 will be here

so row with id = 2 will be here

.

Sorry for my bad explanation i hope this is understandable

heres my code so far

<?php  
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
    $dbdate = $row['date'];
    $dbnews = $row['news'];
    echo "<h1><strong>$dbdate</strong></h1>";
    echo "<div class='content'>$dbnews</div><br><br>";
}
?>

Upvotes: 0

Views: 3796

Answers (7)

Harshal
Harshal

Reputation: 3622

Just replace your code by this code:

<?php  
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
    $dbdate = $row['date'];
    $dbnews = $row['news'];
    echo "<h1><strong>$dbdate</strong></h1>";
    echo "<div class='content'>$dbnews</div><br><br>";
}
?>

Upvotes: 0

Joe G Joseph
Joe G Joseph

Reputation: 24096

try this:

just have to add

order by id DESC

Upvotes: 0

Ben Stephens
Ben Stephens

Reputation: 563

SELECT * FROM news ORDER BY id DESC

DESC is the descending keyword
ASC is ascending

If you specify neither then default behaviour is ascending

Upvotes: 5

James Mitch
James Mitch

Reputation: 549

$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");

However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.

Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().

The advantage is that you can say:

SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC

This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!

Upvotes: 1

Danil Speransky
Danil Speransky

Reputation: 30473

Just use DESC keyword in your sql query.

Upvotes: 1

Dan Dinu
Dan Dinu

Reputation: 33428

   $sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");

Upvotes: 0

John Woo
John Woo

Reputation: 263853

add DESC in your ORDER BY clause

SELECT * FROM news ORDER BY id DESC

by default, it is in ASC mode.

Upvotes: 5

Related Questions