3

I am performing a database query like this:

$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select('*');
$query->from($db->quoteName('#__table_name'));
$query->where($db->quoteName('username') . " = ". $db->quote($user->username));
$db->setQuery($query);

$result = $db->loadResult();

$row = $db->loadrow();
print_r($row); </pre>

The output that I get looks somewhat like this:

Array ( [0] => any_username [1] => val_of_col1 [2] => val_of_col2 [3] => val_of_col3 )

How to convert it into a HTML table?

2 Answers 2

10

Try this:

$rows = $db->loadrow();

echo '<table>';
echo '<tr>';  
   foreach($rows as $row) {
       // display your results here
   }
echo '</tr>';
echo '</table>';

You first echo out the base table structure and then display your results

0
1

Just to clear up a possible misconception about the script in the question...

$result = $db->loadResult(); does not have an active/necessary role to play in the process. $result is not be used after it is declared and it does not "set up" loadRow().

As for how to echo out each column value, I'll recommend implode() as the most concise method. In doing so, it won't matter if you build your result set from loadRow() or loadAssoc() because implode() will ignore the keys. What DOES matter is the columns that you write into your SELECT clause -- this will dictate exactly which columns are presented. It is unlikely that you will want to display ALL of the columns so * should be swapped out for literal column declarations (either as a comma separated string or an array of strings). The snippet to follow will work flawlessly even if you only select a single column (and generate a one dimensional result set).

$db->loadRow() with implode():

if (!$row = $db->loadRow()) {  // declare and check
    echo "No Row Found";
} else {
    echo '<table>';
        echo '<tr>';
            echo '<td>' , implode('</td><td>', $row) , '</td>';
        echo '</tr>';
    echo '</table>';
}

If you would like to display a row of column headings, then use loadAssoc() to generate the result set. If you wish to adjust one or more column headings to be printed to screen, use a "column alias" where appropriate in the SELECT clause of your query.

if (!$row = $db->loadAssoc()) {  // declare and check
    echo "No Row Found";
} else {
    echo '<table>';
        echo '<tr>';
            echo '<th>' , implode('</th><th>', array_keys($row)) , '</th>';
        echo '</tr>';
        echo '<tr>';
            echo '<td>' , implode('</td><td>', $row) , '</td>';
        echo '</tr>';
    echo '</table>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.