Question

Method 1

  global $database;
  $user = new stdClass;
  $user->id = NULL;
  $user->name = $name;
  $user->username = $username;

  if (!$database->insertObject( '#__users', $user, 'id' )) {
    echo $database->stderr();
    return false;
  }

  return $user->id;

Method 2

  $db = JFactory::getDBO();     
  $query = $db->getQuery(true);
  $query->insert($db->nameQuote('#__users'));
  $query->set($db->nameQuote('name').'='.$db->quote($$name).','.
  $db->nameQuote('username').'='.$db->quote($username));     
  $db->setQuery( $query );
  $db->query();
  $new_id = $db->insertId();

I'm using Joomla and use both above queries which lets me the get the work done. My problem is what is the difference between method 1 and method 2? What's the industry standard? Are there any specific situation I should use above methods? Which one is better and why?

Thanks

Was it helpful?

Solution

Method 1 (M1) and Method 2 (M2) are both valid Joomla! 2.5 mechanisms, M1 uses a semi automated method and is probably more commonly used where you are already working with objects.

M2 is obviously a more specific set of steps but both will work the abstraction provided by JDatabase et. al. to isolate you from the database server.

Having said that M1 is only used in a few places (literally) in the entire Joomla! 2.5 installation (not counting /libararies/joomla/database/) while M2 is used extensively

The only odd thing is the use of a global in M1, normally Joomla! coding standards eschew the use of globals preferring rather to use OOP or factory patterns instead. So, something like this:

$database = JFactory::getDBO();

instead of using the global reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top