-1

How can i dynamically set a column name in $wpdb query? i tried

$which_column = 'phone';
$data_check = $wpdb->get_var("SELECT '.$which_column.' FROM wp_shopping_preferences WHERE wp_user_id = '$id'");

but it doesn't work. This however does work

$data_check = $wpdb->get_var("SELECT phone FROM wp_shopping_preferences WHERE wp_user_id = '$id'");

I need the columns to be set dynamically for a shortcode i am building

Regards

2

This is simply a syntax error by the looks of it. You are using " to open the string, and ' to close it. Use this:

$which_column = 'phone';
$data_check = $wpdb->get_var("SELECT " . $which_column . " FROM wp_shopping_preferences WHERE wp_user_id = '$id'");

Fun fact: when using double quotes ("), you can directed insert a variable into the string without closing it~

$which_column = 'phone';
$data_check = $wpdb->get_var("SELECT $which_column FROM wp_shopping_preferences WHERE wp_user_id = '$id'");

EDIT

I noticed that you have $id at the end of the query also being added. **If this is a user-submitted valueyou must use [$wpdb->prepare`]1 to ensure it's sanitized properly. See below:

$which_column = 'phone';
$data_check = $wpdb->get_var( 
    $wpdb->prepare( 
        "SELECT $which_column FROM wp_shopping_preferences WHERE wp_user_id = %d",
        $id 
    )
);

The extra line breaks are unnecessary, but only to demenstrate what's happening. I've replaced$id with %d, which will typecast $id as a numeric value. Check out $wpdb->prepare for more options.

  • tx i didn't realise WP uses two different ways of declaring a $variable within a query. '$id' vs ". $which_column . ' or '$id' vs $which_column – alex Sep 17 '14 at 13:18
  • 1
    See Edit above for a more secure query. – Eric Holmes Sep 17 '14 at 13:19

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.