To prevent SQL injection attacks
defmodule MyApp.UserController do
use MyApp.Web, :controller
def index(conn, params) do
users = MyApp.Repo.query!("SELECT * FROM users WHERE name = '#{params["name"]}'")
render conn, "index.html", users: users
end
end
The Elixir code directly interpolates user input into a SQL query, which could lead to SQL injection attacks if the user input is not properly sanitized.
defmodule MyApp.UserController do
use MyApp.Web, :controller
def index(conn, params) do
users = MyApp.Repo.query!("SELECT * FROM users WHERE name = $1", [params["name"]])
render conn, "index.html", users: users
end
end
The secure Elixir code uses parameterized queries to prevent SQL injection attacks. The user input is no longer directly interpolated into the SQL query, but instead, it is passed as a parameter to the query.