0

I am using following code in the theme files to get some output from the DB:

<?php $querystr = "SELECT DISTINCT meta_value FROM $wpdb->wp_postmeta WHERE 'meta_key' LIKE 'movie_name' ORDER BY meta_value ASC";
$movie_names =  $wpdb->get_results($querystr, OBJECT);
echo sizeof($movie_names);
?>
<ul>
<?php foreach ( $movie_names as $movie_name ){ ?>
   <li><?php echo $movie_name->meta_value; ?> </li>
<?php } ?>
</ul>

Above code's result is "0" at the frontend. But when I am running the same query i.e.

SELECT DISTINCT meta_value FROM wp_postmeta WHERE 'meta_key' LIKE 'movie_name' ORDER BY meta_value ASC

in DB then it's returning 6 rows. Please help me in finding the problem in the code.

1 Answer 1

4

$wpdb->wp_postmeta is wrong. Always use just $wpdb->postmeta – without further prefixes.

So...

global $wpdb;

$querystr = "
    SELECT DISTINCT meta_value 
    FROM $wpdb->postmeta 
    WHERE meta_key LIKE 'movie_name' 
    ORDER BY meta_value ASC
";

$movie_names = $wpdb->get_results( $querystr, OBJECT );

if ( ! $movie_names ) {
    $wpdb->print_error(); // Get the last error message for debugging
}
else {
    // Do something awesome with the movies
}
1
  • Thanks Toscho. Its working now with some little modification.
    – Akhilesh
    Commented Apr 24, 2013 at 16:49

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.