简体   繁体   中英

Getting the last 7 rows from MySQL in PHP

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?

您不会:

SELECT * FROM ... WHERE ... ORDER BY user_id DESC LIMIT 7
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
SELECT * FROM #__mytable WHERE (user_id = '$uid') ORDER BY id DESC LIMIT 0,7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM