I have the feeling that the answer to my problem is going to be very simple. I have written the following code to access a table that I have loaded into my WordPress database. I can run the query in phpMyAdmin. It runs as expected. I have tried everything that I found in an attempt to get it to work.

My Function:

function plcoa_email_address_list () {
    global $wpdb;

    $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM tblLots" );
    echo "<p>Lot count is " . $user_count . "</p>";
    $wpdb->show_errors( true );
    $result = $wpdb->get_results($wpdb->prepare("SELECT LotNum FROM tblLots;" ));
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo $row["email"] . "<br>";
    } else {
        echo " <br>  0 results";
function plcoa_short_code( $atts=null, $content=null ){
    plcoa_email_address_list ();

The result that I get is:

Lot count is 369

WordPress database error: [] SELECT LotNum FROM tblLots;

0 results

  • You need a second parameter to call $wpdb->prepare or you'll get warnings in your PHP logs, since you aren't inserting any variables there's nothing to prepare so that part can be removed. Also why is there a ; in the second query?
    – Tom J Nowell
    Apr 4, 2018 at 23:04

1 Answer 1


Here's your problem:

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

$result is not a mysqli_result object, it's literally the results of the query. Since you never passed a second parameter to the get_results method specifying what format you wanted them in, it'll assume "OBJECT", so the correct usage would be:

$results = $wpdb->get_results("SELECT * FROM tblLots" );
if ( !empty( $results ) ) {
    // output data of each row
    foreach ( $results as $row ) {
        echo $row['email'];

Notice I also corrected an error in the SQL statement, you only asked the database for the LotNum field, then tried to grab the email expecting a full database row, when you only asked for a single column

Notice as well that all of this is detailed in the codex and in the dev hub, on the official wp.org docs

  • Thanks Tom, I've been going crazy trying to figure this out.
    – Bud
    Apr 5, 2018 at 22:31
  • @Bud if it's correct can you mark it as the answer?
    – Tom J Nowell
    Apr 6, 2018 at 0:40

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.