使用wordpress $ wpdb <table> </table>显示数据库内部的数据

时间:2013-09-16 09:20:32

标签: php wordpress html-table

有人可以帮助我,如何编写逻辑以将数据从我的数据库打印到<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

我知道这是如此基本,但我真的很难让这项工作。

4 个答案:

答案 0 :(得分:10)

试试这个:

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

答案 1 :(得分:0)

你只需要将<tr>放在你的foreach循环中,然后在你的行中添加.连接运算符,你就可以了:

  • 您需要将<td></td>包裹在foreach循环中的<tr></tr>
  • 您需要在包含firstname变量的行中添加.并置运算符。
  • 如果您有重复值,请将此参数ARRAY_A添加到您的查询

    $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>
    

答案 2 :(得分:0)

.

中缺少echo '<td>' $print->firstname.'</td>';

试试这个

<?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 :(得分:0)

试试这个:

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

然后是通常的周期:

//spare memory
$count = count($result);
//fastest way to perform the cycle
for ($i = $count; $i--;) {
   echo '<td>'. $print[$i]['firstname'].'</td>';
}