0

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 Answers 2

1

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.

2
  • 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 Commented Sep 17, 2014 at 13:18
  • 1
    See Edit above for a more secure query. Commented Sep 17, 2014 at 13:19
0

I see that in wordpress 6.2 you can do a single column name. https://make.wordpress.org/core/2022/10/08/escaping-table-and-field-names-with-wpdbprepare-in-wordpress-6-1/

$table = 'your_table';
$field = 'user_input_field';
$wpdb->prepare('SELECT %i FROM %i', $field, $table);

(How would you do multiple?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.