• Resolved Abatap

    (@abatap)


    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 2 replies - 1 through 2 (of 2 total)
  • Moderator Marius L. J.

    (@clorith)

    Hi,

    The reason is that $wpdb->prepare() adds quotes around strings for you if it’s not seeing any to begin with, so your query is essentially saying SELECT 'product_price', and since it’s in quotes, that means return that string, not the actual row.

    To make this work, I’m afraid your column value needs to be escaped manually by you, or hard coded.

    I’m seeing that you are grabbing product data from a custom table though, are you sure you can’t use post meta and a CPT for what it is you are doing here ?

    Thread Starter Abatap

    (@abatap)

    Thank you! Unfortunately, all data is located in a separate database so I think cannot use these things wp provides. This example code in my post was just a mockup to demonstrate the issue. I guess I’ll just have to use get_row in both cases and then grab needed column value from there if requested.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Strange $wpdb->get_var behavior’ is closed to new replies.