1

I am trying to get some data from WordPress database tables in a plugin. For that, I am using the below code...

global $wpdb;
$findID = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $findID;

But it not giving me the post ID in echo? Is there anything wrong...???

2
  • I checked again and found that it was my coding problem and after fixing that, the upper one is also working. You can also use the below answer one too... Commented Sep 29, 2014 at 4:29
  • @ialocin Ok. Done... Commented Oct 2, 2014 at 4:27

2 Answers 2

6

Just to clarify the get_var() method of $wpdb does work just fine in this context:

global $wpdb;
$helloworld_id = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $helloworld_id;

Actually it is more practical in this context, because a single variable is returned, which is what is actually wanted.

1
  • Thanks for confirming me that I shared the right code but the problem was in my other codes so its ok now... Commented Oct 2, 2014 at 4:28
3

I found the solution and the correct query to fetch one data from WordPress database is below one.

global $wpdb;
$findID = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $findID[0]->ID;
3
  • Don't know what the problem in your setup was/is but using get_var should work just fine. There shouldn't be the need to use get_results, which in this scenario is additionally a bit impractical. Commented Sep 27, 2014 at 17:54
  • I checked again and found that it was my coding problem and after fixing that, the question one is also working fine. Commented Oct 2, 2014 at 4:29
  • the correct syntax is global $wpdb; $tableName = $wpdb->prefix . 'leaguemanager_person_status'; $findID = $wpdb->get_results("SELECT ID FROM $tableName WHERE post_name = 'hello-world'"); echo $findID[0]->ID; Commented Jul 18, 2021 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.