MySQL creation returns table back

I want to create a simple news system using PHP and MySQL, now I have a working post and a reading system, but there is only one problem, I want it to show the 10 latest news, but instead it shows the 10 oldest news,

My question : is there a way to get MySQL to return results from the bottom of the table or do I need to get the number of posts first and then limit them to the last 10?

Here is the insert (title and text escaped and time is time (), poster not yet done):

mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());

      


And return it (addnews echos it):

$myqr = mysql_query('SELECT * FROM news LIMIT 10') or die("Error running news query: ". mysql_error());
while($myres = mysql_fetch_array($myqr))
{
addnews($myres['id'], $myres['title'], "admin", date('l jS F Y - H:i:s', $myres['time']), $myres['text']);
}

      

So, in short: I want to read the database back, is it possible?

0


a source to share


8 answers


Check out the ORDER BY clause . It allows you to sort rows by column in ascending or descending order. The following query returns 10 news items sorted by time in descending order.



SELECT * FROM news ORDER BY time DESC LIMIT 10

      

+11


a source


Simple, just add an ORDER BY clause to your SQL like



SELECT * FROM news ORDER BY time DESC LIMIT 10

      

+2


a source


you need to change your query to sort by the date it was created. sort of

SELECT * FROM news  order by time DESC LIMIT 10

      

should work for you. I find it worth noting that if you don't specify the Order by option, the order in which the results are returned is not guaranteed. Right now, you happen to be getting them ordered by the time they were inserted in ascending order, however you cannot safely assume that this will always be the case.

+1


a source


Assuming id is the primary key:

SELECT * FROM new ORDER BY id DESC LIMIT 10

      

0


a source


Use the ORDER BY clause.

0


a source


Could you just order by Descending time to LIMIT 10?

0


a source


use

SELECT * FROM news ORDER BY time DESC LIMIT 10

      

0


a source


You can also use

SELECT TOP 10 FROM news ORDER BY time DESC

      

I believe. Not sure if the 'top' clause is only SQL Server.

0


a source







All Articles