WordPress.org

Ready to get started?Download WordPress

Forums

How to use $wpdb in plugin (6 posts)

  1. willx
    Member
    Posted 2 years ago #

    Hello

    I'm trying to use $wpdb from a selfmade plugin. (Because obviously, I want to make my own queries and get the results from db)

    The problem is: I just can't use $wpdb for some reason.
    Even something simple like

    global $wpdb;
    $result = $wpdb->get_results("select * from wp_posts");

    will make my .php file crash and stop doing anything...

    What am I missing or doing wrong?

  2. Kakoma
    Member
    Posted 2 years ago #

    Hi Will,

    $result = $wpdb->get_results("select * from wp_posts");

    isn't really 'something simple'.
    You are basically returning a very big result set; more so if your blog has a big number of posts.
    Try something like:

    $result = $wpdb->get_results("select * from wp_posts where ID='1'");

    Better-still, for an even faster query, don't use the '*' syntax but specify exactly which field(s) you want from wp_posts.

    $first_post_author = $wpdb->get_results("select post_author from wp_posts where ID='1'");

  3. vxxxv
    Member
    Posted 1 year ago #

    I have same problem. how to show the $result? is it work via echo?

  4. vxxxv
    Member
    Posted 1 year ago #

    and another question is about join 3 table. how to do it?i know how to join in sql. i need to learn the way that in wordpress. tnx

  5. webwarrior.wng
    Member
    Posted 1 year ago #

    It is not working... Strange!!!
    In 'bpModBackend.php', when i paste the below code on line 156:

    $mod_status = $wpdb->get_var( $wpdb->prepare( "SELECT status FROM $wpdb->bp_mod_contents;" ) );
    echo $mod_status;

    Even echo anything is working very well!

  6. dmkizer
    Member
    Posted 1 year ago #

    I am trying to do something that falls very much within this discussion. I am not at all literate with PHP though.
    I have two WP sites. I want to reach from one of them, into the other, and retrieve specific featured images for posts, and display them with a link to that post.

    I am using this line (with the correct info for my target database):
    $mydb = new wpdb('username','password','database','localhost');

    What would I follow that with to retrieve and display a post thumbnail?

    I am tinkering with a line of code I found elsewhere that looks like this:

    $result = $mydb->get_results("select * from wp_posts where ID='1885'");

    where '1885' is a sample post ID number.

    In an ideal world, I would develop this to the point where it functions as a widget. The client could simply enter a post ID number from the external WP site, and the widget would retrieve the appropriate thumbnail, and display it as a link back to the appropriate post on the other site.

Topic Closed

This topic has been closed to new replies.

About this Topic