Question

My SQL skills are a little limited but I can figure out how to query things the long way. Is there a better way to do this SQL statement below in one action instead of separating it into like three?

$db = JFactory::getDbo();
                $query = "SELECT email FROM xx_opencart_customer WHERE customer_id = '".$this->session->data['customer_id']."'";
                $db->setQuery($query);
                $results = $db->loadObjectList();
                foreach ($results as $t) {;
                }

                $db = JFactory::getDbo();
                $query = "SELECT id FROM xx_users WHERE email = '".$t->email."'";
                $db->setQuery($query);
                $results = $db->loadObjectList();
                foreach ($results as $t) {;
                }

                $db = JFactory::getDbo();
                $query = "SELECT group_id FROM xx_user_usergroup_map WHERE user_id = '".$t->id."'";
                $db->setQuery($query);
                $results = $db->loadObjectList();
                foreach ($results as $t) {;
                }

The end result I am able to tell what $t->group_id equals to.

Was it helpful?

Solution

Try this:

$db = JFactory::getDbo();
$query = "SELECT z.group_id 
          FROM #__opencart_customer x, #__users y, #__user_usergroup_map z 
          WHERE x.customer_id = ".
          $db->quote($this->session->data['customer_id']).
          " AND x.email = y.email AND y.id = z.user_id";
$db->setQuery($query);
$result = $db->loadResult();

For single value results, you don't need to use $db->loadObjectList();
For table names, don't use the actual dbprefix. Use #_ instead. This way you can change table prefix from configuration.php without changing the queries.
Also, no need to set $db = JFactory::getDbo(); everytime. Once is enough!

Hope this helps.. Cheers!

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