WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] $wpdb-> query and $wpdb->get_col strange result (10 posts)

  1. axxxon
    Member
    Posted 3 years ago #

    hello!
    i'm looking for help with $wpdb->query and $wpdb->get_col.
    I'm trying to get id's of my posts from table wp_posts.
    but when i run
    $wpdb->query("SELECT id from wp_posts")
    i get just first id, and when i use
    $wpdb->get_col("SELECT id FROM wp_posts",0);
    i got over 300 ids, while i have only 30 posts(tho the rest are revisions and autosaves from this 30 posts).
    i tried to use $wpdb->prefix and $wpdb->posts but effect was the same.
    I'd appreciate any help.

  2. Joseph
    Member
    Posted 3 years ago #

    You need to set criteria such as post type and status:
    $wpdb->query("SELECT id FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");

  3. axxxon
    Member
    Posted 3 years ago #

    still same result, i used Yours query Joseph and got only 1st id...
    it's strange for me, but i'm still trying to find resolution...
    even after adding limit 0,30 nothing change... when i checked query in phpmyadmin everything worked fine.

  4. Joseph
    Member
    Posted 3 years ago #

    Sorry my mistake. $wpdb->query returns an integer of the number of rows selected/affected.

    Change query to get_col

    $wpdb->get_col("SELECT id FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");

    This will give you an array of post IDs.

  5. artcoder
    Member
    Posted 3 years ago #

    For me $wpdb->query() and $wpdb->get_results() and $wpdb->get_col() are all giving me ...

    Fatal error: Call to a member function get_col() on a non-object

    I'm calling this from a PHP file kind of outside WP plugins, so I've ...

    include_once('wp-config.php');
    include_once('wp-load.php');
    include_once('wp-includes/wp-db.php');

    at the top of PHP file.

    How can I call the WP database from outside a plugin?

  6. Joseph
    Member
    Posted 3 years ago #

    Did you declare global $wpdb; before doing the query?

  7. artcoder
    Member
    Posted 3 years ago #

    I forgot. Thanks.

  8. axxxon
    Member
    Posted 3 years ago #

    well i globalize the $wpdb and did includes as artcode and strilee the same...
    anyone know why its stiill error?

  9. Joseph
    Member
    Posted 3 years ago #

    What error are you referring to?

    global $wpdb;
    $id_array = $wpdb->get_col("SELECT id FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");

    It should work. I've tried it just to make sure.

  10. axxxon
    Member
    Posted 3 years ago #

    everything working fine now, after i've just restarted mysql server.
    thx for help!
    cheers!

Topic Closed

This topic has been closed to new replies.

About this Topic