Display data from database inside using wo

2019-03-21 16:50发布

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

i know this is so basic, but im really having a hard time to make this work.

4条回答
欢心
2楼-- · 2019-03-21 17:03

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>';
}
查看更多
唯我独甜
3楼-- · 2019-03-21 17:13

You just need to put <tr> inside your foreach loop ,and add . concatenation operator in your line ,you nee alsotry 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>
    
查看更多
家丑人穷心不美
4楼-- · 2019-03-21 17:14

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>';
  }
?>  
查看更多
乱世女痞
5楼-- · 2019-03-21 17:21

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 }
  ?>              

查看更多
登录 后发表回答
向帮助了您的知道网友说句感谢的话吧!