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;

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

echo $mypost;

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


If you want generic result you can use $wpdb->get_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


$mypost = $wpdb->get_var($wpdb->prepare("SELECT post_content FROM $wpdb->posts WHERE ID = %d", 2));
| improve this answer | |
  • 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 – facebook-100001191095620 May 23 '14 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)); – facebook-100001191095620 May 23 '14 at 7:37
  • what is the error. show it – ksr89 May 23 '14 at 7:38
  • I have posted the error at previous comment . Please see. – facebook-100001191095620 May 23 '14 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 '14 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.