how to access Joomla 2.5!: Classes for Accessing Database for mysql

For select Query:

$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 insert Query:
$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 udate Query:
$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();

For fetch multiple row:

Your Query goes here
$items = $db->loadObjectList();


For fetch Single row:

Your Query goes here
$book_item = $db->loadObject();


Advertisements

2 thoughts on “how to access Joomla 2.5!: Classes for Accessing Database for mysql

  1. Typo detected – You forgot the “p” in Update, in the header for your third example.

    Also, don’t forget chaining… your select example could be shortened to:

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

    Nevertheless – good compilation of examples for beginners, here!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s