Tom Tom - 1 year ago 86
PHP Question

joomla using multiple database queries in one function

In certain functions I may need to do a couple of queries like so:

$user = & JFactory::getUser();
$db = & JFactory::getDBO();
$query = $db->getQuery(true);

$user_id = $db->loadResult();

if ($user_id == "")
//do something

$query1 = $db->getQuery(true);
$query1->where('app_descr='.$db->quote($this->app_descr).' AND app_valid=TRUE');
$app_id = $db->loadResult();

I find if I don't change
I can't get this to work for the subsequent queries. Outside of Joomla I've never had to do this as I close the mysql connection use the same variable as long as it is in the right order, all is well.

Two questions:

  1. Is this right? Or is there a better way to do this?

  2. Do I need to check for mysql failure of
    ? How would I go about this. Looking at the Joomla core often I see nothing but sometimes there is a mix of things to handle this.

Answer Source

1) It should work with the same variable name, since you are getting a new query object since your method parameter is set to true. Try calling $query->clear(); just after getting query object

$query  = $db->getQuery(true);

2) In Joomla 3 it should be something like

    $user_id = $db->loadResult();
catch (RuntimeException $e)

And in Joomla 2.5

if ($db->getErrorNum()) {
    JError::raiseWarning(500, $db->getErrorMsg());

Also, change

$user = & JFactory::getUser();
$db = & JFactory::getDBO();


$user = JFactory::getUser();
$db = JFactory::getDBO();

Objects are returned by reference anyway in PHP 5, and it will throw a warning since php 5.3+

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download