Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PersonalHomePage's avatar

how to prevent sql injection with DB::select(DB::raw($query))

I thought that if I use something like this


$myQuery = "SELECT * FROM myTable where id = :id";
DB::select(DB::raw($myQuery), ['id' => $id]);

this will use my raw sql query and the 2nd array param is where I declare the variables that should be escaped to prevent sql injection, but I'm seeing in version 5.6 this isn't the case. I'm not sure if I'm using it in correctly. Anyone have some suggestions for me? my objective is to prevent sql injection while passing user input to raw queries through query builder. Appreciate any help with this one, ty.

0 likes
6 replies
Snapey's avatar

why do you need to use a raw query?

1 like
PersonalHomePage's avatar

@Snapey Short answer : I'm better at writing my own sql queries because I'm still getting familiar with Eloquent. Also, the query itself is more complicated than the example, but I'm curious why I can't escape the variable to prevent sql injection. It seemed to work in other code for me, but in this instance it doesn't. Does it matter how complicated the query is? That seems the be the only difference to me.

Please or to participate in this conversation.