Display data from database inside <table> using wordpress $wpdb

Can someone help me, how to code the logic to print the data from my database into a <table>?

<table border="1">
    <tr>
     <th>Firstname</th>
     <th>Lastname</th>
     <th>Points</th>
    </tr>
    <tr>
      <?php
        global $wpdb;
        $result = $wpdb->get_results ( "SELECT * FROM myTable" );
        foreach ( $result as $print )   {
            echo '<td>' $print->firstname.'</td>';
            }
      ?>
    </tr>               
</table>

table

Read More

I know this is so basic, but I’m having a hard time making this work.

Related posts

Leave a Reply

4 comments

  1. Try this:

    <table border="1">
    <tr>
     <th>Firstname</th>
     <th>Lastname</th>
     <th>Points</th>
    </tr>
      <?php
        global $wpdb;
        $result = $wpdb->get_results ( "SELECT * FROM myTable" );
        foreach ( $result as $print )   {
        ?>
        <tr>
        <td><?php echo $print->firstname;?></td>
        </tr>
            <?php }
      ?>              
    

  2. You’re missing . in echo '<td>' $print->firstname.'</td>';

    Try this

    <?php
      global $wpdb;
      $result = $wpdb->get_results ( "SELECT * FROM myTable" );
        foreach ( $result as $print )   {
    
          echo '<tr>';
          echo '<td>' . $print->firstname.'</td>';
          echo '<td>' . $print->lastname.'</td>';
          echo '<td>' . $print->points.'</td>';
          echo '</tr>';
      }
    ?>  
    
  3. Try this:

    $result = $wpdb->get_results("SELECT * FROM myTable" , ARRAY_A); //get result as associative array
    

    Then the usual cycle:

    //spare memory
    $count = count($result);
    //fastest way to perform the cycle
    for ($i = $count; $i--;) {
       echo '<td>'. $print[$i]['firstname'].'</td>';
    }
    
  4. You just need to put <tr> inside your foreach loop, and add . concatenation operator in your line, you need also try this :

    • You need to wrap <td></td> inside <tr></tr> in foreach loop

    • You need to add . concatenation operator in line that contains firstname variable.

    • If you have duplicate values, then add this parameter ARRAY_A to your query

      $result = $wpdb->get_results ( "SELECT * FROM myTable",ARRAY_A );.

       <table border="1">
           <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Points</th>
           </tr>
      
             <?php
               global $wpdb;
               $result = $wpdb->get_results ( "SELECT * FROM myTable" );
               foreach ( $result as $print )   {
                 echo '<tr>';
                 echo '<td>' . $print->firstname .'</td>';
                         echo '<td>' . $print->lastname  .'</td>';
                         echo '<td>' . $print->points    .'</td>';
                 echo '</tr>';
                   }
             ?>
      
       </table>