R1ddler
R1ddler

Reputation: 47

Extracting columns from sql table with php

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.

Upvotes: 1

Views: 86

Answers (2)

Progrock
Progrock

Reputation: 7485

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>

Upvotes: 1

Ahmed Sunny
Ahmed Sunny

Reputation: 2243

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>";

Upvotes: 1

Related Questions