How is this MySQL query vulnerable to SQL injection?


In a comment on a previous question, someone said that the following sql statement opens me up to sql injection:

    ss.*, as engine,
    ss.last_run_at + interval ss.refresh_frequency day as next_run_at,
    searches ss join search_engines se on ss.engine_id =
group by
order by ss.project_id, ss.domain, ss.keywords

Assuming that the $userid variable is properly escaped, how does this make me vulnerable, and what can I do to fix it?

Assuming it is properly escaped, it doesn't make you vulnerable. The thing is that escaping properly is harder than it looks at first sight, and you condemn yourself to escape properly every time you do a query like that. If possible, avoid all that trouble and use prepared statements (or binded parameters or parameterized queries). The idea is to allow the data access library to escape values properly.

For example, in PHP, using mysqli:

$db_connection = new mysqli("localhost", "user", "pass", "db");
$statement = $db_connection->prepare("SELECT thing FROM stuff WHERE id = ?");
$statement->bind_param("i", $user_id); //$user_id is an integer which goes
                                       //in place of ?