Using parameters to escape data
We used where("user.name = :name", { name: "Timber" })
. What does { name: "Timber" }
stand for? It’s a parameter we used to prevent SQL injection. We could have written: where("user.name = '" + name + "')
, however this is not safe, as it opens the code to SQL injections. The safe way is to use this special syntax: where("user.name = :name", { name: "Timber" })
, where :name
is a parameter name and the value is specified in an object: { name: "Timber" }
.
.where("user.name = :name", { name: "Timber" })
is a shortcut for:
.where("user.name = :name")
.setParameter("name", "Timber")
Note: do not use the same parameter name for different values across the query builder. Values will be overridden if you set them multiple times.
You can also supply an array of values, and have them transformed into a list of values in the SQL statement, by using the special expansion syntax:
.where("user.name IN (:...names)", { names: [ "Timber", "Cristal", "Lina" ] })
Which becomes:
WHERE user.name IN ('Timber', 'Cristal', 'Lina')