mysqljoomlajoomla2.5joomla3.0joomla3.1

Joomla Database - How to use LIMIT in getQuery?


I want to build the below query using joomla inbuilt database class.

SELECT * 
FROM table_name
ORDER BY id DESC
LIMIT 1

This is the query I have built up to now.

$db =& JFactory::getDBO();       
$query  = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));      
$db->setQuery($query);      
$rows = $db->loadObjectList();

I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks


Solution

  • Older than Joomla 3.0

    $db = JFactory::getDBO();    
    
    $query  = $db->getQuery(true);
    $query->select('*')
     ->from($db->nameQuote('#__table_name'))
     ->order($db->nameQuote('id').' desc');     
    $db->setQuery($query,0,1);  
    
    $rows = $db->loadObjectList();
    

    $db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.

    Newer than Joomla 3.0

    setLimit(integer $limit, integer $offset)
    

    If you want just one row

    $query->setLimit(1);
    

    Read more