0

I am learning wordpress database, And I have written this query for showing the data from the post table with id=2, but not showing anything. What is wrong with the following query? please help.

global $wpdb;
$wpdb->show_errors();

$mypost=$wpdb->query($wpdb->prepare("SELECT post_content FROM $wpdb->wp_posts WHERE     ID=%d",2));

echo $mypost;

1 Answer 1

2

First of all your query is wrong. The right query is

$mypost = $wpdb->query($wpdb->prepare("SELECT post_content FROM $wpdb->posts WHERE ID = %d", 2));

Second the $wpdb->query will returns an integer value indicating the number of rows affected/selected. You can check here

http://codex.wordpress.org/Class_Reference/wpdb#General_Syntax

If you want generic result you can use $wpdb->get_results

http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results

$mypost = $wpdb->get_results($wpdb->prepare("SELECT post_content FROM $wpdb->posts WHERE ID = %d", 2));

For getting single value result you can also use $wpdb->get_var

http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable

$mypost = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM $wpdb->posts WHERE ID = %d", 2));
5
  • Not working. Here is the error I am getting: WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ID=2' at line 1] SELECT post_content FROM WHERE ID=2 May 23, 2014 at 7:36
  • I am getting the error when I am using : $mypost = $wpdb->get_results($wpdb->prepare("SELECT post_content FROM ".$wpdb->posts." WHERE ID = %d", 1)); May 23, 2014 at 7:37
  • what is the error. show it
    – ksr89
    May 23, 2014 at 7:38
  • I have posted the error at previous comment . Please see. May 23, 2014 at 7:40
  • check this query $mypost = $wpdb->get_results($wpdb->prepare("SELECT post_content FROM $wpdb->posts WHERE ID = %d", 2)); In your query table name is not present.
    – ksr89
    May 23, 2014 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.