what is the best way to sanitize this STRING to prevent SQL Injection?
$order_by_str = 'dest ASC';
EDIT
$whitelist = array('start','target','exec');
if ( in_array( $order_by, $whitelist ) ) {
$order_by_str = $order_by;
} else {
$order_by_str = 'start';
}
I used now this, it seems to work for me.
Given answers don't answer the question.
Although there is no way for the general purpose "string sanitization", one may notice that the given string is a very special one.
And the only way to sanitize it is whitelisting.
A best way to sanitize this string would be to have both parts separated and then both checked against whitelist.
So, instead of having this string whole, I'd have it in 2 variables, $_GET['orderby']
and $_GET['dir']
.
And so the code would be
$allowed = array("dest","foo","whatever");
$key = array_search($_GET['orderby'], $allowed));
$orderby = $allowed[$key];
$dir = $_GET['dir'] == 'DESC' ? 'DESC' : 'ASC';
$query = "SELECT * FROM t ORDER BY $orderby $dir";