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
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
JDatabaseet. 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 extensivelyThe only odd thing is the use of a
globalin M1, normally Joomla! coding standards eschew the use of globals preferring rather to use OOP or factory patterns instead. So, something like this:instead of using the
globalreference.