The table is like this:

category_id   category_name   category_parent_name

I would like to get category_id by using category_name. I searched online, and the code is like below:

$ad_cat is the category name.

global $wpdb;
  $tbl_categories = $wpdb->prefix."awpcp_categories";
   $retrieve_data = $wpdb->get_results( "SELECT * FROM $tbl_categories where category_name =".$ad_cat );

I echo'ed category name and id for testing. The name shows fine, but id is always 0. Any idea or solution?

  • What is var_dump($retrieve_data); ? – s_ha_dum Jun 21 '13 at 0:39
  • array(1) { [0]=> object(stdClass)#483 (1) { ["category_name"]=> string(20) "Fitness and Exercise" } } The fitness and exercise id should be 5 – Pluto Jun 21 '13 at 0:44
  • If you ran SELECT * on that table and only got category_name then your table does not look like you say it does. – s_ha_dum Jun 21 '13 at 2:01

Use the method get_var() instead. I've also tidied up your code (if you're gonna use double quotes, take advantage of them!) & added data escaping with the handy prepare() method.

global $wpdb;

$cat_id = $wpdb->get_var(
        "SELECT category_id FROM {$wpdb->prefix}awpcp_categories WHERE category_name = %s",
  • It works! Thank you so much. I have question about the answer: what do mean when you say"take advantage of using double quotes...?" – Pluto Jun 21 '13 at 14:08
  • Also, is there any different between get results and get var? – Pluto Jun 21 '13 at 14:10
  • @Pluto Check out the codex on wpdb for a rundown of the different methods. PHP will interpret variables in double quotes, so no need to concatenate (join with dots). – TheDeadMedic Jun 21 '13 at 21:56

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.