get_results using wpdb

I’m trying to retrieve information on my database. I wanted to display all pages using this statement, but I’m getting a blank ARRAY

global $wpdb;
$result = $wpdb->get_results (
        "
        SELECT * 
        FROM  $wpdb->wp_posts 
        WHERE post_type =  'page'
        "
        );

echo $result; // display data

Output:

Read More
  ARRAY

EDIT: After changing below suggestions, I’m now using this. but I still don’t get any results:

global $wpdb;

    $posts = $wpdb->wp_posts;
    $result = $wpdb->get_results( " SELECT * FROM  $posts WHERE 'post_type' =  'page' "  );

    foreach ($result as $page) {
            echo $page->ID.'<br/>';

    }

Related posts

4 comments

  1. global $wpdb;
    
    $result = $wpdb->get_results ( "
        SELECT * 
        FROM  $wpdb->posts
            WHERE post_type = 'page'
    " );
    
    foreach ( $result as $page )
    {
       echo $page->ID.'<br/>';
       echo $page->post_title.'<br/>';
    }
    
  2. You have a slight misunderstanding:

    When calling $wpdb, you get a list of properties that contain the core names of the tables:

    // The custom prefix from wp-config.php
    // only needed for custom tables
    $wpdb->prefix
    
    // Tables where you don't need a prefix: built in ones:
    $wpdb->posts
    $wpdb->postmeta
    $wpdb->users
    

    So your final query would look like this:

    $wpdb->get_results( "SELECT * FROM {$wpdb->posts} WHERE post_type = 'page'" );
    
  3. Try the following code. I faced the similar problem and solved it by removing $wpdb from ‘FROM’ field.

    global $wpdb;
    $result = $wpdb->get_results (
                "
                SELECT * 
                FROM  wp_posts 
                WHERE post_type =  'page'
                "
                );
    
    echo $result; // display data
    

Comments are closed.