Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

Abatap on "Strange $wpdb->get_var behavior"

$
0
0

Hello, guys. I'm having a weird problem with a seemingly trivial task. Lets say I have a simple wrapper function to acquire certain variables from database using the wpdb class functionality wordpress provides.

Here is an example code:

$result = get_product_data($product_id, 'product_price');

echo $result; // prints 'product_price' instead of acquired column value

//returns whole row if the second arg is not set
function get_product_data($id, $column_to_get = null) {

  global $wpdb;

  if (isset($column_to_get)) {

    //strange behavior here
    return $wpdb->get_var($wpdb->prepare('SELECT %s FROM '.$wpdb->prefix.'shop_products WHERE product_id=%d', $column_to_get , $id));

  } else {

    //this one works just fine
    return $wpdb->get_row($wpdb->prepare('SELECT * FROM '.$wpdb->prefix.'shop_products WHERE product_id=%d', $id), ARRAY_A);

  }
}

The problem seems to be related to the second arg we feed to $wpdb->prepare here as hardcoding it in the query string itself gives you an expected result. So what is the problem here? Is this some bizzare php expression evaluation quirk or am I doing something terribly stupid?


Viewing all articles
Browse latest Browse all 8245

Trending Articles