Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 );
$category_id=intval($retrieve_data->category_id);

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

share|improve this question
    
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
add comment

1 Answer

up vote 1 down vote accepted

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(
    $wpdb->prepare(
        "SELECT category_id FROM {$wpdb->prefix}awpcp_categories WHERE category_name = %s",
        $ad_cat
    )
);
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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