skip to Main Content

Am trying to fetch the data from the database into the WordPress plugin via SQL query. However, the loop is not working even though it is not showing any error. I tried many things on the internet but nothing of them is working. Here is my code below:-

Query Code:

<?php
        function vssp_settings() {
        global $wpdb;
        $result = $wpdb->get_results ( "SELECT * FROM students_list" );
        foreach( $result as $print) {
           
?>

Showing the query result:

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

}
?>

2

Answers


  1. In WordPress, the get_results function returns an array of stdClass objects, not associative arrays, by default. Therefore, you need to access the elements as object properties using the arrow operator (->), rather than as array indices with square brackets ([]).

    Ensure that your table name (‘students_list’) is correct and actually exists in your database. If the table name varies or relies on the WordPress prefix, you should employ $wpdb->prefix . ‘your_table_name’.

    As a precautionary measure, always check if $result is not empty before proceeding with a foreach loop to avoid potential issues.

    To gain more detailed insight into potential errors, consider enabling debugging in WordPress. This can be done by adding the following line to your wp_config.php file: define( 'WP_DEBUG', true );. This will provide a more comprehensive error output for diagnosis.

    Login or Signup to reply.
  2. do a var_dump($result);

    and wrap the foreach in a condition like if ($result) {...}

    See get_results/

    Try $print->… instead of $print["…"]

    $output

    Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
    With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, …), a numerically indexed array (0 => value, …), or an object ( ->column = value ), respectively.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search