0

I have a block of code that works perfect:

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array($db->quoteName('date')));
$query->from($db->quoteName('#__webfoot_minutes_and_agendas'));
$query->order('date DESC'); 
$db->setQuery($query);
$results = $db->loadObjectList();

Until I try to assign it to a function:

function call_db() {
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select(array($db->quoteName('date')));
    $query->from($db->quoteName('#__webfoot_minutes_and_agendas'));
    $query->order('date DESC'); 
    $db->setQuery($query);
    $results = $db->loadObjectList();   

    return $results;
}

It breaks when I try to call the function, I get an error for $results I get, "Invalid argument supplied for foreach()...:

call_db();

foreach ($results as $result) {
   $dateArr = explode('-', $result->date);
       if (!in_array($dateArr[0], $already_echoed)) {
         echo '<li><a href="#tabs-' . $count . '">' . $dateArr[0] . '</a></li>';
       $count++;
       }
     $already_echoed[] = $dateArr[0];
}

Anyone have any suggestions on how I can straighten out this syntax?

BradM
  • 646
  • 8
  • 18

3 Answers3

2

You have to assign result of your function to variable.

$results = call_db();
marian0
  • 3,336
  • 3
  • 27
  • 37
1

Though it is awful design:

foreach (call_db() as $result) { ... }
moonwave99
  • 21,957
  • 3
  • 43
  • 64
0

You haven't assigned return value of call_db() to anything. You have to assign it first to $results

$results = call_db();

And, after that it is better if you check that the $results is an array. See this.

Community
  • 1
  • 1
nisargjhaveri
  • 1,469
  • 11
  • 21