HTML 表在使用 $WPDB 时形成 MYSQL 和 PHP

HTML tables form MYSQL with PHP while using $WPDB

您好,我正在尝试在使用 $wpdb 连接到 MYSQL table 的同时,在 wordpress 短代码中创建一个带有 PHP 的 table。我已经写了/找到了如何使用基本 PHP 和传统连接来执行此操作,但是我编写的代码不起作用,我确定我错过了一些东西。有人可以在下面的代码中告诉我哪里出错了吗?谢谢

全球 $wpdb;

$wpdb->query( $wpdb->prepare("SELECT * FROM wp_wpdatatable_4"));
    $result=mysql_query(query);
    $numfields = mysql_num_fields($result);
    echo "<table border=1><tr>";

    for ($i=0; $i < $numfields; $i++) // Header
    { echo '<th>'.mysql_field_name($result, $i).'</th>'; }

    echo "</tr>";

    while
    ($res=mysql_fetch_row($result))   //you may use mysql_fatch_array($result) which can hendel both $res[name] and $res[1]
    {
    echo"
    <tr>
    <td>  $res[0]</td>
    <td>  $res[1]</td>
    <td>  $res[2]</td>
    .
    .
    .
    </tr>";
    }

    echo"</table>";

}

您的代码结合使用了 $wpdb 和 php mysql 函数。

也许只需要使用 $wpdb

global $wpdb;

$data_table_4 = $wpdb->get_results( "SELECT * FROM wp_wpdatatable_4" ); 

if ( ! empty( $data_table_4 ) ) {
    echo '<table>';
    if ( ! empty( $data_table_4 ) ) {
        foreach ( $data_table_4 as $data_table_4_row ) { 
            echo '<tr>';
            foreach ( $data_table_4_row as $row_item ) {
                echo '<td>' . $row_item . '</td>';
            }
            echo '</tr>';
        }
    }
    echo '</table>';    
}