0

What is the basic way to use $wpdb and get_results?

This is my code:

global $wpdb;
$q="SELECT * FROM wp_usermeta WHERE meta_key = 'nickname' AND user_id = 771";
$result = $wpdb->get_results($q);
echo $result;

The query string is good because I can run it in phpmyadmin and it works fine. I am not getting anything back when run through page.

1 Answer 1

2

$wpdb->get_results() returns an array on success, so you can't simply echo $result;.

Instead, you can use foreach to loop through the results and display whatever the data that you want to display:

$results = $wpdb->get_results( $q );
foreach ( $results as $row ) {
    echo $row->meta_value . '<br />';
}

But I can see that you're trying to select just one row, so you'd want to use $wpdb->get_row() and not $wpdb->get_results():

$row = $wpdb->get_row( $q );
if ( $row ) {
    echo $row->meta_value;
}

But then again — because wp_usermeta is the default table for WordPress users' meta, if you just want to retrieve the meta value, then there's a function you can (and should better) use — get_user_meta():

echo get_user_meta( 771, 'nickname', true );
2
  • Thank you! get_user_meta worked perfectly. I might try the other options as well just for my own edification. Thanks again May 24, 2020 at 22:48
  • Awesome. :) And would you please kindly mark the answer as correct? Doing so would help others know the question has an accepted solution.
    – Sally CJ
    May 24, 2020 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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