Please someone tell me what is wrong in my code and where I need to change it
P粉147045274
2023-07-31 17:05:37
<p>I'm trying to pull data from a database into a WordPress plugin via a SQL query. However, the loop doesn't work even though no errors are shown. I tried many methods on the internet but none of them worked. Here is my code:</p><p><br /></p>
<pre class="brush:php;toolbar:false;"><?php
function vssp_settings() {
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM students_list" );
foreach( $result as $print) {
?></pre>
<p>Display query results:</p>
<pre class="brush:php;toolbar:false;"><td><?php echo $print["first_name"];?></td>
<td><?php echo $print["last_name"];?></td>
<td><?php echo $print["email"];?></td>
<td><?php echo $print["phone"];?></td>
<td><?php echo $print["address"];?></td>
<?php
}
}
?></pre>
<p><br /></p>
In WordPress, by default, the get_results function returns an array of stdClass objects instead of an associative array. Therefore, you need to use the arrow operator (->) as an object property to access elements instead of using square brackets ([]) as an array index.
Make sure your table name ('students_list') is correct and actually exists in your database. If the table name changes or relies on WordPress prefix, you should use $wpdb->prefix . 'your_table_name'.
As a precaution, always check if $result is empty before doing a foreach loop to avoid potential problems.
For more detailed error information, consider enabling debugging in WordPress. You can do this by adding the following line to your wp_config.php file: define( 'WP_DEBUG', true );. This will provide more comprehensive error output for diagnostic purposes.