php - How to use prepare() with dynamic column names? -
i have function takes sql table column name string parameter, returns 1 string result:
function myfunction($column_name) { return $wpdb->get_var($wpdb->prepare("select %s mytable user_id=%s", $column_name, $current_user->user_login)); }
however, code not work, since nature of prepare, can't use variable column names (and table names).
this works, think poses security issue:
return $wpdb->get_var('select ' . $column_name . ' mytable user_id=' . $current_user->user_login);
what need in order to use dynamic column names in prepare statement?
you use list of "approved" values instead, way you're not using user data inside query. this:
$approved = array ('firstname', 'lastname', 'birthdate') ; $location = array_search($columnname, $approved) // returns approved column location int if($location !== false) { // use value approved using $location key $query = $wpdb->prepare('select ' . $approved[$location] . ' mytable user_id=:userid'); $query->execute(array( :userid => $current_user->user_login )); return $query; } else { return false; }
maybe might easier (select * or select a,b,c,d) of user data , save session use later?
Comments
Post a Comment