Tuesday, May 29, 2012

Joomla 2.5!: Classes for Accessing Database

For selecting:

$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('field1,fieldn');
$query->from('#__tablename');
$db->setQuery((string)$query);
$results = $db->loadObjectList();
if ($results){
    foreach($results as $result) 
    {
        //$result->field1
        //$result->fieldn;
    }
}


For inserting:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert('#__tablename');
$query->set("field1='value1', fieldn='valuen'");
$db->setQuery($query);
$db->query();
To get the last insert id, use:
$db->insertid();

For udating:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->update('#__tablename');
$query->set("field1='value1', fieldn='valuen'");
$query->where("fieldx='valuex'");
$db->setQuery($query);
$db->query();

For simple query:

$db = JFactory::getDbo();
$query = "<YOUR QUERY>";
$db->setQuery($query);
$db->query();

2 comments:

Subscribe to RSS Feed Follow me on Twitter!