Support » Fixing WordPress » $wpdb-> query and $wpdb->get_col strange result

  • Resolved axxxon


    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.

Viewing 9 replies - 1 through 9 (of 9 total)
  • 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'");

    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.

    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.

    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 …


    at the top of PHP file.

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

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

    I forgot. Thanks.

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

    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.

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

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘$wpdb-> query and $wpdb->get_col strange result’ is closed to new replies.