I am working on a wordpress site, and started implanting a CRUD database. I coded out an example that works perfectly on my localhost. However, I am working with file mangaer in cpanel, and am having difficulty with changing the regular database query to a one that is incorporated with $wpdb. I have tried to use $wpdb->get_results(), but I get the same error. Any help would be greatly appreciated.

Here is my code:

    $query = "SELECT * FROM students";
    $query_results = mysqli_query($wpdb->dbh, $query) or die(mysqli_error($wpdb->dbh));

    if(mysqli_num_rows($query_results) > 0) 
        foreach($query_run as $student)
            echo '
                <form id="saveStudent">
                        echo '<td>'<?php $student->id; ?> echo '</td>';
                        echo '<td>'<?php $student->first_name; ?> echo '</td>';
                        echo '<td>'<?php $student->last_name; ?> echo '</td>';
                        echo '<button type="button" class="btn btn-danger">Delete Student</button>'

            echo '</tr>';

EDIT: The error message I get is Warning: mysqli_query() expects parameter 1 to be mysqli, null given

  • Where is this file? Is it someplace inside a theme or plugin where other WordPress functions are working?
    – WebElaine
    Oct 17, 2022 at 21:10
  • I am working within the cart page, under the web hook woocommerce_before_cart. The file itself is included in the functions.php file which is apart of cpanel's file manager
    – John Lyons
    Oct 17, 2022 at 21:14
  • Have you declared global $wpdb; before trying to use the global $wpdb object?
    – Pat J
    Oct 18, 2022 at 2:08

1 Answer 1


Use the global $wpdb object to query your tables. The get_results() method will return your results as you need:

global $wpdb;

$query = 'SELECT * FROM students';
$query_results = $wpdb->get_results($query);
foreach ($query_results as $student) {
    // ...
  • When I tried that out, I got Fatal error: Uncaught Error: Call to a member function get_results() on null
    – John Lyons
    Oct 18, 2022 at 13:59
  • @JohnLyons check your spelling $wpdb and ensure you are calling this from a WordPress or WooCommerce hook so that the global variable has been defined.
    – webaware
    Oct 18, 2022 at 22:59
  • e.g. add_action('woocommerce_before_cart', function() : void { ... });
    – webaware
    Oct 18, 2022 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.