Making MySQL return the table backwards - php

I want to make a simple news system using PHP and MySQL, right now I got a working post and read 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: Is there a way to make MySQL return the results from the bottom of a table or do I have to first get the number of posts and then limit it to the very last 10 ones?
Here is the insert (title and text is escaped and time is time(), poster is not done yet):
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
And to retrive 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, short: I want to read the database backwards, is it possible?

Check out the ORDER BY clause. It allows you to sort rows by a column in ascending or descending order. The following query will return 10 news items, sorted by time in descending order.
SELECT * FROM news ORDER BY time DESC LIMIT 10

Simple, just add an "ORDER BY" clause to your SQL, e.g.
SELECT * FROM news ORDER BY time DESC LIMIT 10

you need to modify your query to sort by the date it was created. something like
SELECT * FROM news order by time DESC LIMIT 10
should work for you. I think its worth noting that if you do not specify an Order by clause, the order in which results are returned is not guaranteed. Right now, you happen to be getting them ordered by the time they were inserted ascending, however you cannot safely assume that will always be the case.

Assuming that id is the primary key:
SELECT * FROM new ORDER BY id DESC LIMIT 10

Use an ORDER BY clause.

Could you not simply Order By time Descending before LIMIT 10?

use
SELECT * FROM news ORDER BY time DESC LIMIT 10

You could also use
SELECT TOP 10 FROM news ORDER BY time DESC
I believe. Not sure if the 'top' clause is SQL Server only, though.

Related

Complex SQL Query - Popular Content

So, I'm writing a query to select data from the database, and display it in an order of popularity. I understand that this is simple enough to do if it were just ordering it through something such as ORDER BY numLikes DESC or something, but in this case, I am wanting to order the content by numLikes and through datePosted.
How would I sort the content in a way that it displays the top content from today's date? If it sorted purely through numLikes, The top content would float to the top and stay there. I want this content to be sorted through a daily basis. This is to allow for a system where the user can choose popular posts from the past day, past week, past month, and all time top posts.
Could this be done through a single SQL query? Would an SQL multi-query have to be done? Is SQL powerful enough to do this, or is PHP required to play a role?
Thanks!
You just need to sort on datePosted first and then by numLikes. Something on the following lines:
SELECT * FROM tableName ORDER BY datePosted, numLikes DESC
If you want top post between a particular range, you can do:
SELECT TOP 1 * FROM tableName
WHERE datePosted BETWEEN [MinDate] AND [MaxDate]
ORDER BY datePosted, numLikes DESC
Replace [MinDate] and [MaxDate] with the dates you need, e.g. for the past week, they would be something like April-14 and April-20.

Reversing the display of mysql_fetch_array on html page

I have a discussion type page, where users can enter their replies on different subjects. For this, I have a table name replies with fields replyID, topicID, userID, replybody, time
On the page, where I display the result, I use this php command:
$run = mysql_query("SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5");
while($data= mysql_fetch_array($run)){
// do formatting and display data
}
as you can see, the page initially displays only 5 replies on a topic (after which, if interested, user clicks to visit the page where all replies are displayed).
the thing is, the above code displays correctly the recent 5 replies, but I want to change the order of its display. It shows the recent most reply on top, and older replies are displayed as we go down, but I want to change this order, showing the recent most reply on bottom.
I think I'm missing a very simple point here, since most of the website have this feature where recent most comments go down, but hey, "no question is small".
I don't think that's very easy in sql.
I would just load the results in an array and use array_reverse() to reverse the order. Then you can loop through the array and display the values like you do now.
Otherwise I think you need to do 2 queries, one to get the total amount and then one to limit your result set to the last x items.
Use a nested query to reverse the order in SQL:
SELECT *
FROM (
SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5
) AS a
ORDER BY time ASC
The inner query will return your most recent 5 records, while the outer query will reverse the sort order of those 5.

PHP/MySQL Sort By Date

I'm trying to pull records out of my database based on the oldest date.
The MySQl table looks like this:
status, date, last, url
1, 2010-12-30 17:59:54, 2011-01-03 06:26:04, site1.com
1, 2010-12-28 12:16:10, 2011-01-03, 06:25:24, site2.com
The date and last rows are datetime.
Here are two types of queries I tried:
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY last DESC LIMIT 0,25");
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY DATE(last) DESC LIMIT 0,25");
The query works for the most part but always leaves some of the oldest records out...
Any ideas?
Thank you
I'm going to assume "last" means last clicked or updated right? I also think you want ascending order (12/20, 12/21) because you want the oldest dates first. "ORDER by last LIMIT 25" should be fine as ASC is implicit.
What are date and last's data types? timestamp or ?
try this:
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY UNIX_TIMESTAMP(last) DESC LIMIT 0,25");

How to select the most recent 10 records

I have a mysql database. How do I select the most recent 10 records? Im not storing timestamps. But the most the recent records are the ones at the bottom rite? Also. How so I get the next ten , the next ten and so on on clicking a button. Kinda like a bunch of forum posts. The recent ones show up first.
I believe you have an auto increment column as a primary key you can use this column and to order by desc
select * from table order by id desc limit 10
otherwise you have a very poor database design
If you have an AUTO_INCREMENT column you can order by that in descending order then limit by 10.
But I suggest you store timestamps and order by that instead so you know you're sorting your records according to date, and not some other value that coincides with date of insertion.
In addition to what #BoltClock mentioned, prequerying the maximum ID might help the engine with what other records are retrieved... ie: if you have a million records, and most recent 10, I don't know if it will still try to query out the million, order them, and THEN dump it.. I would try something like
select STRAIGHT_JOIN
YT.*
from
( select max( IDColumn ) as MaxOnFile
from YourTable ) PreQuery,
YourTable YT
where
YT.IDColumn >= PreQuery.MaxOnFile -10
order by
YT.IDColumn DESC
limit 10
However, if for some reason, records are allowed to be deleted, you may opt to subtract a little farther back than the -10... but at least this way, the system won't even TRY to process all the other records...

PHP - MySQL display highest ID number

What SQL query would I use to display the newest entry?
Details:
id is the primary field. I have other fields but that are not related to when they were added.
ORDER BY SomeColumn DESC
LIMIT 1
or
use the MAX() function
Since you didn't give any details about your table it is hard to answer
SELECT * from yourTable ORDER BY `id` DESC LIMIT 1;
Another (better) way would be to have a "date_added" column (date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP) so you could order by that column descending instead. Dates are more reliable than ID-assignment.
not sure if this is what your looking for but I use mysql_insert_id() after inserting a new row
The auto incremented ID columns are not always the latest records inserted, I've remember really painful experience with this behavior. Conditions where specific, it was mysql 4.1.x at the time and there was almost 1 million records, where 1 out of 3 deleted everiday, and others re inserted in the next 24hours. It made a huge mess when I realize ordering them via ID was not ordering them by age....
Since then, I use a specific column for doing age related sorts, and populating these fields with date = NOW() at each row insert.
Of course it will work to found the latest record as you want, doing an ORDER BY date DESC LIMIT 0,1on your query
SELECT Primary_Key_Field FROM table ORDER BY Primary_Key_Field DESC LIMIT 1
Replace Primary_Key_Field and table obviously :)

Categories