php - Pass sanitized input as column name in where clause -
i have function accepts $filter
argument , pulls data sql table based on filters in argument. @ first tried overloading function 1 function took single $filter
variable , took array multiple filters. then, started wondering how sanitize filter tag.
that may have been confusing here examples. example, user types in search box display users name john. so, $filter_tag
set 'name' , $filter
set 'john'. pdo query this:
$query = "select `name` `users` "; $query .= $filter_tag." = ?";
the issue $filter_tag
not sanitized. if sanitize , variable escaped, query not work. maybe making more complicated needs , there simple solution.
please comment if not understand asking.
you create whitelist of valid tags:
if (in_array($filter_tag, ['name', ...], true)) { $query .= $filter_tag . = '?'; }
alternately remove invalid characters, prefer whitelist approach, because there many valid column names :)
lastly, instead of above code turn condition around , raise error if given tag doesn't appear in whitelist. in cases may better approach, because otherwise may error later on because number of arguments passed ->execute()
should match number of placeholders in query.
Comments
Post a Comment