0

I have a dynamic query for filtering, and now I have a problem where I need to use DB::raw for ordering by

$this->query->orderBy(\DB::raw("POSITION(\"$value\" IN $column)", 'asc'))

But now here I have a SQL Injection protection issue, how can I prevent $value and $column from SQL Injection without using ->setBindings

I cant use ->setBindings 'cause I have dinamic numbers of filter columns depending on the table

3 Answers 3

3

Prepared statements can't evaluate column names, so you need to use whitelisting to protect against injections into $column.

To protect against value, you can either force it to be an integer or float type, or use orderByRaw which accepts an array of parameters:

$this->query->orderByRaw("POSITION(? IN $column)", [$value])
Sign up to request clarification or add additional context in comments.

2 Comments

actually I don't need protection to $column cause it's from an array that I create, it works perfectly, thank you
You might want to put $column in back-ticks just in case it matches a reserved word.
1

You could use orderByRaw which will accept an array of bindings.

$this->query->orderByRaw('POSITION(? IN ?) asc', [$value, $column]);

2 Comments

You can't use parameters for column names.
This solution won't return an error, but it'll treat the second parameter as a literal string, not the name of a column. So it won't do what the OP wants.
-1

Try the below,

$orderByQuery = "select * from table order by POSITION(:value IN :column) asc";
$this->query->select($orderByQuery, [
    "value" => $value,
    "column" => $column
])

Comments

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.