tags:

views:

136

answers:

3

I'm trying to get the last 7 records from a table whose records were entered by the user

Here is my query:

$database->setQuery("SELECT * FROM #__mytable WHERE (user_id = '$uid')");
$dberr="";
if (!$database->query()) {
    $dberr = $database->getErrorMsg();
}

if(!$dberr==""){
   echo($dberr."<br>");
}else{
   $rows = $database->loadObjectList();

How do I cycle thru the $rows to get the last 7?

+3  A: 
SELECT  *
FROM    #__mytable
WHERE  user_id = '$uid'
ORDER BY
       entered_date DESC
LIMIT 7

To get them in ascending order, use:

SELECT  *
FROM    (
        SELECT  *
        FROM    #__mytable
        WHERE  user_id = '$uid'
        ORDER BY
               entered_date DESC
        LIMIT 7
        ) q
ORDER BY
        entered_date
Quassnoi
+2  A: 
SELECT * FROM #__mytable WHERE (user_id = '$uid') ORDER BY id DESC LIMIT 0,7
erenon
+5  A: 

You don't:

SELECT * FROM ... WHERE ... ORDER BY user_id DESC LIMIT 7
mst
Why do you order the resoult by user_id?
erenon
I assumed the user IDs are incremental and unique, and thus would serve well as default clustering order of the whole table. You have to sort by a key, otherwise the results are unpredictable and will vary widely accross platforms/database engines/library versions/phase of the moon.
mst
`@mst`: `user_id` is filtered on in the original query.
Quassnoi
That's perfectly fine. You can sort by other keys, or by keys that are used in WHERE conditions or the keys (fields) that are omitted from the SELECT statement.
mst
But to get the last seven, ordering by user_id doesn't make sense.
erenon
"Last 7" can only apply to an ordered list. It makes no sense in any other context. Without an explicit sorting order, "last 7" is identical to "arbitrary 7". I don't know the actual layout of the OP's schema - I merely presume that user_id is a primary key.
mst