Skip to content
Advertisement

WordPress PHP get_results query from MySQL DB not working

I’m using the following PHP code to attempt to fetch values from the DB of all entries with ‘ID’ equal to 5055. It doesn’t return any result, and I’m not sure what’s wrong…

<?php
function displayMyLinks() {
global $wpdb;
 
$results = $wpdb->get_results ( " SELECT * FROM $wpdb->sm_links WHERE ID = 5055 " );
foreach ( $results as $link )
{
    //NOT WORKING
    echo $link->ID;
    echo $link->url;
    echo $link->description;
    echo $link->favourite;
    
}
}

Advertisement

Answer

I presume this is a local webpage you’re working on. If so, here’s a couple of debugging techniques here:

function displayMyLinks() {
    global $wpdb;
    $sql = "SELECT * FROM %s WHERE ID = %d";

    $results = $wpdb->get_results(sprintf($sql, $wpdb->sm_links, 5055));
    if (! count($results)) {
        var_dump($wpdb);
    }

    foreach ($results as $link) {
        var_dump($link);
    }
}

It may be worthwhile to check the table you’re querying to ensure you’re asking for columns that exist there:

    global $wpdb;
    $sql = "describe $wpdb->sm_links";
    var_dump($wpdb->get_results($sql));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement