1

My query selects all columns from my table

$spool = $wpdb->get_results('SELECT * FROM `tablename`');

then I display the results in a table. I need to display all columns. This is the way I do it.

echo "<table>";
  if ( !empty( $spool ) ) {
      echo  "<tr><th> header </th></tr>";
             foreach ( $spool as $a ) {
                    echo "<tr><th>" . $a->columnname1 . "</th><th>" .$a->columnnameN . "</th></tr>";
                }   

    }
echo "</table>";

Now since I have around 40 columns, I'd like to ask if there is a more intelligent and less tedious way of displaying them.

10
  • share a screenshot or fiddle Commented Sep 14, 2017 at 15:16
  • for 40 columns and you want to show all, usually x-axis scroll on table div . and condensed table, less padding in cells etc Commented Sep 14, 2017 at 15:17
  • My question is a php one. Instead of doing $a->columnname for each of them, is there a shorter way to write it and still display all of them. Commented Sep 14, 2017 at 15:22
  • I know that I can display them all if I wrote $a->columnname for every single column but that would be tedious. Commented Sep 14, 2017 at 15:23
  • What is $a an instance of? Commented Sep 14, 2017 at 15:24

2 Answers 2

1

probably you need nested loops, you are getting result probably like this

array(
    0:{column1:test,column2:test . . . },
    1:{column1:test,column2:test . . . }
)

so you can try this way

    echo "<table>";
    if ( !empty( $spool ) ) {
      echo  "<tr><th> header </th></tr>";
        foreach ( $spool as $key => $value  ) {
           echo '<tr>';
             foreach ( $value as $a ) {
                      echo "<th>" . $a. "</th>";
                 }   
            echo '</tr>';
          }
      }
      echo "</table>";
Sign up to request clarification or add additional context in comments.

Comments

1

As you have objects you could cast them to arrays and use implode. (But attribute order could be different from what you want.)

<?php
class A
{   
    public $foo = 'bing'; 
    public $bar = 'bang';
    public $baz = 'bong';    
}
$spool = [new A, new A];

echo '<table>';
foreach($spool as $a) {
    echo '<tr>';
    echo '<td>' . implode('</td><td>', (array) $a) . '</td>';
    echo '</tr>';
}
echo '</table>';

Output:

<table><tr><td>bing</td><td>bang</td><td>bong</td></tr><tr><td>bing</td><td>bang</td><td>bong</td></tr></table>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.