Rendering Database Results in WordPress Tables
You have a database query that returns an array of objects, and you need to render those rows inside an HTML <table>. The snippet you posted demonstrates the core concept: using $wpdb->get_results() to fetch data and looping through it with foreach. However, there are several structural issues in that specific code block that prevent it from rendering correctly, ranging from syntax errors to missing loop logic for columns.
The primary error lies within the echo statement inside your loop. In PHP, you cannot simply concatenate a variable directly into a string without wrapping it in curly braces or quotes if mixed with other text, and HTML tags must be properly quoted. The line:
echo '<td>' $print->firstname.'</td>';
fails because $print->firstname is not enclosed in quotes to be treated as a string literal for concatenation, nor does it handle the closing </tr> tag which sits outside the loop in your example. If you want to print multiple columns (Firstname, Lastname, Points), every cell needs its own <td> tag, and the row must close after the last column.
To render a clean table header followed by dynamic data rows, you should separate the HTML structure from the PHP logic as much as possible. Start by defining the headers outside the loop to ensure they appear exactly once. Then, iterate through your result set to build each row dynamically.
Here is a robust pattern using $wpdb->get_results():
global $wpdb;
// Fetch data from myTable
$results = $wpdb->get_results("SELECT firstname, lastname, points FROM myTable", ARRAY_N);
// Using ARRAY_N returns rows as indexed arrays (0, 1, 2) instead of objects if column names aren't needed.
echo '<table border="1">';
echo '<tr>';
echo '<th>Firstname</th>';
echo '<th>Lastname</th>';
echo '<th>Points</th>';
echo '</tr>';
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . esc_html($row[0]) . '</td>'; // Index 0 corresponds to firstname
echo '<td>' . esc_html($row[1]) . '</td>'; // Index 1 corresponds to lastname
echo '<td>' . esc_html($row[2]) . '</td>'; // Index 2 corresponds to points
echo '</tr>';
}
echo '</table>';
There are critical security implications here that often get overlooked in basic tutorials. The $wpdb class is designed to prevent SQL injection, but the output rendering requires attention too. Never echo raw database values directly into HTML without sanitization. An attacker could inject malicious scripts if a name field contains <script> tags. Always use esc_html() when outputting strings to ensure special characters like <, >, and & are converted to their HTML entities, effectively neutralizing XSS vectors.
If you prefer working with object properties rather than array indices, change your fetch method to return objects:
$results = $wpdb->get_results("SELECT firstname, lastname, points FROM myTable");
foreach ($results as $user) {
echo '<td>' . esc_html($user->firstname) . '</td>';
}
This approach improves readability significantly. However, remember that get_results() by default returns an array of objects where property names match column names exactly.
When dealing with large datasets, printing every single row into the DOM can degrade performance and browser responsiveness. If your table exceeds a few hundred rows, consider implementing pagination or virtual scrolling. Additionally, ensure you are using strict typing for your PHP files (e.g., declare(strict_types=1);) to catch potential issues early, such as accessing undefined array indices.
If you find yourself needing more advanced data manipulation or caching strategies around these queries, the Laravel ecosystem offers robust abstractions that might simplify complex database interactions. For instance, if your WordPress site eventually migrates to a framework like Laravel, the underlying logic for querying and rendering tables remains similar, but the ORM capabilities become significantly richer. You can read more about handling such migrations at https://laravelcompany.com.